Common Ruby methods on collections

Blocks in Ruby are methods without a name. Ruby comes with many methods which you can apply on collections. In most cases, you would not use for loops in Ruby.

Here are some common methods to get you started.

each - executes block and returns the list of objects without mutating

# prints 246810 and returns [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5].each {|x| print x*2}

map - executes block and returns the list of mutated objects

[1, 2, 3, 4, 5].map {|x| x*2}
# => [2, 4, 6, 8, 10] 

select - returns a list of objects when condition is true

[1, 2, 3, 4, 5].select {|x| x==2}
# => [2] 

reject - returns a list of objects when condition is false

[1, 2, 3, 4, 5].reject {|x| x==2}
# => [1, 3, 4, 5] 

uniq - returns a list without duplicates

[1, 2, 3, 3, 3, 4].uniq 
# => [1, 2, 3, 4] 

reverse - reverse the list

[1, 2, 3, 4].reverse
# => [4, 3, 2, 1] 

compact - return all non-nil objects

[1, 2, 3, nil, nil, 4].compact
# => [1, 2, 3, 4] 

flatten - flatten inner arrays

[[3,2], [4,4]].flatten
# => [3, 2, 4, 4] 

partition - Create two collections. First collection for true, second for false.

[1, 4, 5, 6].partition {|x| x==4||x==5}
 => [[4, 5], [1, 6]] 

sort without argument - Sorts the list

[31, 34, 11, 23, 1, 3].sort
# => [1, 3, 11, 23, 31, 34]
This was posted 11 months ago. It has 1 note.
  1. allfuzzy posted this