Here are some frequently used methods that use block syntax, along with usage examples.
** Returns the result of evaluating the block for each element as a new array ** A process that prepares an empty array and stuffs the results of looping other arrays into an empty array. 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 a 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 for which the return value of the block 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]
console
irb(main):012:0> ['ruby', 'java', 'perl'].map(&:upcase)
=> ["RUBY", "JAVA", "PERL"]
"Introduction to Ruby for Professionals"
Recommended Posts