[Ruby basics] Methods that frequently use blocks

Here are some frequently used methods that use block syntax, along with usage examples.

map (alias method is collect)

** 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]

Write concisely with & and symbols

console


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

References

"Introduction to Ruby for Professionals"

Recommended Posts

[Ruby basics] Methods that frequently use blocks
Ruby basics
Ruby basics
Methods that I found useful in Ruby
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
Basics of Ruby
Ruby Learning # 15 Methods
[Ruby] Methods that can be used with strings
About Ruby methods
[Ruby basics] How to use the slice method
[Ruby] Exception handling basics
Ruby Learning # 31 Object Methods
About Ruby instance methods
Ruby on Rails basics
Ruby variables and methods
[Ruby] methods, instance methods, etc ...