Fork me on GitHub

Array in ruby short tutorial: ruby way for ruby noobs

Arrays in ruby the ruby way (with code blocks).

Instanciate an array from words

>> els = %w(one two three four five)
=> ["one", "two", "three", "four", "five"]

Iterate over the array

>> els.each { |el| puts el }
one
two
three
four
five

Build an array invoking a code block on each element

>> els.map { |el|  el.reverse }
=> ["eno", "owt", "eerht", "ruof", "evif"]

Return only elements matching a criteria

>> els.select { |el| el =~ /t/ }
=> ["two", "three"]

Reject all elements matching a criteria

>> els.reject { |el| el =~ /t/ }
=> ["one", "four", "five"]

Combine all elements applying a code block

>> els.inject('my elements are') { |str, el| str += ' ' + el }
=> "my elements are one two three four five"

Leave a Reply

*

captcha *