Strings in RUBY
Simply in Ruby or any other language, Strings is a sequence of one or more characters. It can consist of numbers, letters, or symbols.
Let's learn to put a string together. It's common that we want to combine strings into a larger sentence. For Eg:
your_first_name = "John"
your_last_name = "Doe"
your_first_name+ " " + your_last_name
Or we can also embed values inside another string. In Ruby, this is called string interpolation
your_full_name = "John Doe"
puts "Hello, #{your_full_name}, How are you?"
#=> "Hello, John Doe, How are you?"
Using String Interpolation calls to_s method, this means we can use any objects without running into a TypeError exception. For using the string interpolation we need to use double-quotes. Single quotes ignore all the special characters.
For Eg:
age = 19
name = "Shyam"
puts "#{name} is #{age} years old now"
#=> Shyam is 19 years old now"
String Concatenation
There is another method to concatenate two strings. We used String#+ which creates a new string While using String#<< method does not create a new string. Creating new strings is slower than changing an already existing string.
For eg:
sentence = ""
# => ""
sentence << "Nepal "
# => "Nepal "
sentence << "is "
# => "Nepal is "
sentence << "beautiful "
# => "Nepal is beautiful"
String justification
There are ljust & rjust methods in ruby that allow us to align in a column.
names_with_ages = [
["ram", "14"],
["shyam", 16"],
["hair", 20]
]
names_with_ages.each do |name, age|
puts name.ljust(10) + age.to_s
end
# => ram 14
shyam 16
hair 20
Manipulating String
The gsub method is a useful method to replace parts of the string or even remove them. For Eg:
"One of my friends loves to play with cats".gsub("cats", "dogs")
#=> "One of my friends loves to play with dogs"
It can be used to replace all the strings in an array and the Regexp.union method to replace multiple words at the same time. For Eg:
animals_to_replace = ["tiger", "Elephant", "snakes"]
text = "In this Zoo we have trigers, elephants & snakes"
text.gsub(Regexp.union(animals_to_replace), "cats")
we can also use with block:
"a1 b2 c3".gsub(/\d+/) { |number| number.next }
Splitting Strings
We can break string using split method. By default, the split will use whitespace as the separator. The split method returns an array which we can put together again by using join.
str = "AmLn-123"
puts str.split("-")
#=> ["AmLn", "123"]
We can also use the sting like array for indexing and getting one character or some of them
For eg:
"Hello Nepal"[o..4]
# => "Hello"
"Hello Nepal"[1..-1]
# => "ello Nepal"
Working with characters
each_char and chars methods
"Nepal is beautiful".each_char { |ch| puts ch }
chars is equivalent to each_char.to_a:
"Many more".chars
# => ["M","a","n",",y"," " ,"m","o","r", "e","e"]