I have a Ruby array containing some string values. I need to:
Right now my solution looks like this:
def example matchingLines = @lines.select{ |line| ... } results = matchingLines.map{ |line| ... } return results.uniq.sort end
Is there an Array or Enumerable method that combines select and map into a single logical statement?
The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.
The map() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum.
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
I usually use map
and compact
together along with my selection criteria as a postfix if
. compact
gets rid of the nils.
jruby-1.5.0 > [1,1,1,2,3,4].map{|n| n*3 if n==1} => [3, 3, 3, nil, nil, nil] jruby-1.5.0 > [1,1,1,2,3,4].map{|n| n*3 if n==1}.compact => [3, 3, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With