[Ruby] [Ruby basics] Methods that frequently use blocks

less than 1 minute read

We will summarize the frequently used methods that use block syntax, along with example usage.

map (alias method is collect)

Return the block evaluation result for each element as a new array Prepare an empty array and fill the empty array with the result of looping other arrays. Most are replaced by the map method.

console



irb(main):026:0> numbers
=> [1, 2, 3, 4, 5]
irb(main):027:0> new_numbers = numbers.map {|n| n * 10}
irb(main):028:0> new_numbers
=> [10, 20, 30, 40, 50]
irb(main):029:0> numbers
=> [1, 2, 3, 4, 5]

select/find_all/reject

**The select method is a method that evaluates the block for each element and returns an array whose return value is a collection of true elements. **

console



irb(main):003:0> numbers = [1,2,3,4,5,6]
irb(main):004:0> even_numbers = numbers.select {|n| n.even?}
rb(main):006:0> even_numbers
=> [2, 4, 6]

The reject method is the opposite of the select method and returns an array excluding the elements whose block return value is true

console


irb(main):007:0> numbers = [1,2,3,4,5,6]
irb(main):008:0> non_multiples_of_three = numbers.reject {|n| n %3 == 0}
irb(main):010:0> non_multiples_of_three
=> [1, 2, 4, 5]

Write briefly using & and symbol

console


irb(main):012:0> ['ruby','java','perl'].map(&:upcase)
=> ["RUBY", "JAVA", "PERL"]

References

“Introduction to Ruby for Professionals”

Tags:

Updated: