ruby arrays short tutorial: ruby way for ruby noobs

Ruby arrays the ruby way (with code blocks).

Instanciate an array from words

[cc lang=”ruby”]
>> els = %w(one two three four five)
=> [“one”, “two”, “three”, “four”, “five”]
[/cc]

Iterate over the array

[cc lang=”ruby”]
>> els.each { |el| puts el }
one
two
three
four
five
[/cc]

Build an array invoking a code block on each element

[cc lang=”ruby”]
>> els.map { |el| el.reverse }
=> [“eno”, “owt”, “eerht”, “ruof”, “evif”]
[/cc]

Return only elements matching a criteria

[cc lang=”ruby”]
>> els.select { |el| el =~ /t/ }
=> [“two”, “three”]
[/cc]

Reject all elements matching a criteria

[cc lang=”ruby”]
>> els.reject { |el| el =~ /t/ }
=> [“one”, “four”, “five”]
[/cc]

Combine all elements applying a code block

[cc lang=”ruby”]
>> els.inject(‘my elements are’) { |str, el| str += ‘ ‘ + el }
=> “my elements are one two three four five”
[/cc]

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *