Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, is there an Array method that combines 'select' and 'map'?

Tags:

ruby

I have a Ruby array containing some string values. I need to:

  1. Find all elements that match some predicate
  2. Run the matching elements through a transformation
  3. Return the results as an array

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?

like image 514
Seth Petry-Johnson Avatar asked Jul 30 '10 12:07

Seth Petry-Johnson


People also ask

How do I map an array in Ruby?

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.

Does map create a new array Ruby?

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.

How do you add an array together in Ruby?

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).

Can you use map with hash Ruby?

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.


1 Answers

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]  
like image 129
Jed Schneider Avatar answered Nov 10 '22 05:11

Jed Schneider