4 Useful Techniques to Manipulate Arrays and Strings in Ruby

Takehiro Mouri
Learning How to Code
2 min readMar 4, 2016

Ruby comes with several useful techniques that you can use to manipulate various data types. In this post, I’ll go over some particularly useful techniques that can be used with arrays and strings in Ruby.

Using %w{ } to declare an array of strings

You can declare an array of strings like this:

array = [‘I’, ‘am’, ‘a’, ‘little’, ‘pony’] 
# [“I”, “am”, “a”, “little”, “pony”]

There’s another way you can declare strings that don’t contain strings, which you may find a to be pretty convenient:

array = %w{I am a little pony} 
# [“I”, “am”, “a”, “little”, “pony”]

It takes less time to type but results in the same thing.

Using find_index

To find the index of an object in array, the find_index method comes in handy:

words = %w{I am a little pony} 
words.find_index{|word| word == “pony”}
# returns 4

The Inject Method

When you want to get the sum of all numbers in an array, the inject method allows you to do so in an elegant way:

numbers = [1, 2, 3, 4, 5] 
numbers.inject{|sum, num| sum += num}
# returns 15

inject is like an each loop, in that it iterates through each element of the array and performs something with each element. inject takes in 2 arguments. The first argument (sum) is the result of the expression performed in the block. In this case, it is the result of sum += num. The second argument (num) is the element in the array in which the iteration is currently on. For example, the first time around, num will equal 1, the second time around, num will equal 2.

sum by default is initialized at 0, but you can specify another value like such:

numbers = [1, 2, 3, 4, 5] 
numbers.inject(100){|sum, num| sum += num}
# returns 115

in which case it returns 115.

No more escapes with %q{ }

Isn’t it annoying when you have to do something like this?

string_full_of_escapes = ‘I\’m in love with Ruby. “Ruby isn\’t just a language, it\’s a lifestyle”. ’

Instead, you could simple do this:

no_escape_string = %q{I’m in love with Ruby. “Ruby isn’t just a language, it’s a lifestyle.”}

The q stands for quotes, and it invokes single quotes for you. Beware that #{} won’t work with single quotes, and only works with double quotes. In that case, you want to use Q%{ } instead:

name = “Takehiro” %Q{My name is #{name}} 
# “My name is Takehiro”

Happy coding!

I write about coding in my personal blog. Every now and then, I share coding articles that I’ve found or written that you might find to be useful or interesting. Subscribe here.

If you found the post useful, please recommend and follow :)

--

--