3

Is there a good way to map and (select or delete_if) at the same time? At the moment, I do either of the following, but was wondering if there is a better way. Also, I cannot use the second one if I want a falsy value within the resulting array.

some_array.select{|x| some_condition(x)}.map{|x| modification(x)}

some_array.map{|x| modification(x) if some_condition(x)}.compact
noodl
  • 17,143
  • 3
  • 57
  • 55
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    Similar question: http://stackoverflow.com/questions/5152098/skip-over-iteration-in-enumerablecollect but no good answers. – Andrew Grimm Mar 22 '12 at 01:32
  • possible duplicate of [In Ruby, is there an Array method that combines 'select' and 'map'?](http://stackoverflow.com/questions/3371518/in-ruby-is-there-an-array-method-that-combines-select-and-map) - which has a better answer – fotanus Jun 26 '14 at 02:54

2 Answers2

2

How about this?

new_array = some_array.inject([]) do |arr, x|
  some_condition(x) ? arr << modification(x) : arr
end

Anytime I think about mapping then selecting or mapping then rejecting etc..., it usually means I can use an enumerable to get the job done.

Kyle
  • 21,978
  • 2
  • 60
  • 61
2

Almost the same to reduce or inject

new_array = some_array.each_with_object([]) do |m,res|
  res << modification(x) if some_condition(x)
end

The difference is that you don't need to put result at the end of block.

megas
  • 21,401
  • 12
  • 79
  • 130
  • Didn't know each_with_object. Neat! – noodl Mar 22 '12 at 00:26
  • Check it here: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_with_objectvvvvvv – megas Mar 22 '12 at 00:30
  • In `rails console` it works but not in `irb`. OP is asking about pure ruby. Are you sure this method exists in pure ruby for arrays? It does for hashes. – Kyle Mar 22 '12 at 00:36
  • I've sent you a link to pure ruby, but i edited it several times, so please check it again. – megas Mar 22 '12 at 00:37
  • BTW, i didn't undo your answer – megas Mar 22 '12 at 00:38
  • Edit your answer so I can give you your vote back but this does **not** work for me using pure ruby 1.9. BTW I did check this before downvoting. Didn't work. – Kyle Mar 22 '12 at 00:40
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/9165/discussion-between-megas-and-kyle) – megas Mar 22 '12 at 00:43