Split string to an array
One common task that you probably want to learn how to do is spliting a string into an array (like explode function in PHP). You can do this by calling “split” method. By default it will split a string on whitespace, but you can pass it a delimiter. Delimiter can be a string or regular expression.
1 2 3 4 5 6 7 | animals = 'dog wolf cat lynx tiger' animals.split # => ["dog", "wolf", "cat", "lynx", "tiger"] "6534-234-23-45".split "-" # => ["6534", "234", "23", "45"] calc = "45 + 36 - 25 * 14" calc.split /\s*[-+*]\s*/ # => ["45", "36", "25", "14"] |
Substitute part of a string
We can do this in two ways. First one is by calling “gsub” method upon a string, and this is quite a usual way. Second one may seem strange at first but it’s quite nice actually. You can substitute a substring like this: my_string["string_to_substitute"] = “replacement_string”. Take a look at the example.
1 2 3 4 5 6 7 | my_statement = "I like dogs" print my_statement.gsub "dogs","cats" # => "I like cats" print my_statement # => "I like dogs" my_statement["dogs"] = "cats" # => "I like cats" print my_statement # => "I like cats" |
Notice that in first case we didn’t make changes upon a string, “gsub” method just returned a new version of a string and left “my_statment” as it is. If you want to make changes upon a string you could use “gsub!” method.
This is a ruby convention, so every time you see a method that ends with “!” you should be careful because it will change the object it is called upon.
String concatenation
You can “glue” one string on another simply with a + or a << operator.
If you want to insert a string in a string, simply use “insert” method, it takes 2 parameters, first is position where to insert the string and second is the string that you want to insert.
1 2 3 4 | part1 = "walk" part2 = "dog" result = part1 + part2 # => walkdog result.insert 4, " a " # => walk a dog |
Cut off last character
You can cut out last character of your string using “chop” method. “chop” also comes with “chop!” version that will make a change on a string, and not just return a new version of a string.
1 2 3 4 5 | string = "Animals" puts string.chop # => "Animal" puts string # => "Animals" string.chop! puts string # => "Animal" |
CHANGEING CaSE of A STRing
Ruby supports easy case changing for entire strings. It includes changing all characters to lower case using the “downcase” method and changing string to all caps with “upcase” method.
1 2 | "A normal string".downcase # => "a normal string" "A normal string".upcase # => "A NORMAL STRING" |
But ruby can do even cooler stuff. Like capitalizing strings, and swapping case of all characters. When capitalizing strings only first character will be in upper case, it won’t do capitalization for each sentence.
1 2 3 | "this is NICE!".capitalize # => "This is nice!" "this is NICE! but could be nicer.".capitalize # => "This is nice! but could be nicer." "this is NICE!".swapcase # => "THIS IS nice!" |








