Ruby Language for Beginners Part 3 - Ruby Strings

DZone 's Guide to

Ruby Language for Beginners Part 3 - Ruby Strings

Welcome back! In today's edition of this series, we take a quick look at using strings in Ruby to do all kinds of neat things!

· Web Dev Zone ·
Free Resource


This is a post from the Ruby Language for Beginners in 8 Parts!

In the today's post, we're going to look at Ruby Strings.

Ruby Strings

A Ruby string can be created using quotes. You start the string with a quote and finish the string with a quote.

Example: "My String in Ruby"

1 - Concatenating Strings

puts "Hacking " + "Code"

2 - Variable With Strings

site = "Hacking " + "Code"
puts site

3 - Concatenating Different Types in Ruby

Let's try to concatenate a number with a string:

number = 10
puts "Hacking Code " + number

If we execute:

ruby-strings.rb:7:in `+': can't convert Fixnum into String (TypeError)
from ruby-strings.rb:7:in `<main>'

In Ruby, for the above code to work, we must convert it first. Let's use the " to_s" method from the Fixnum object when, in this case, the variable is number.

number = 10
puts "Hacking Code " + number.to_s

4 - Interpolating Strings

Sometimes we can have the following code:

java = "Java"
ruby = "Ruby"
go = "Go"
devops = "Docker"
hacking_tutorials = "Hacking Code Tutorials: " + java + ", " + ruby + ", " + go + ", " + devops
puts hacking_tutorials

The output will be:

Hacking Code Tutorials: Java, Ruby, Go, Docker

But it's easy to get lost in this String concatenation. In this case, it is better to use String Interpolation:

hacking_tutorials = "Hacking Code Tutorials: #{java}, #{ruby}, #{go}, #{devops}"
puts hacking_tutorials

Much better, isn't it?

5 - String Interpolation Evaluating Expression

We can evaluate expressions with Ruby Interpolation

final_value = "The sum of the values is #{first_value + second_value}"
puts final_value

And the result will be 15.

Important: This works since we're using double quotes in the String interpolation!

With single-quoted strings, Ruby will just understand the string literally.

# Trying to Interpolate a Ruby String with single quotes
first_value = 10
second_value = 5
final_value = 'The sum of the values is #{first_value + second_value}'
puts final_value

The output will be the following, without the interpolation:

The sum of the values is #{first_value + second_value}

So, we can use single quotes when we need to use the literal strings!

That's it!

In the next post: Part 4 - Ruby Classes, Objects, and Instances we're going to see Ruby Classes, Objects, and Instances!

I hope that would be useful to you!


concatenation, ruby, strings, web dev

Published at DZone with permission of Alexandre Gama . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}