Ee0505bbd355292778077fb662c88f13

I want to collect all the elements from a array which is set to 1 in another array.
Basically I need an reject_with_index() or something, because my solution is ugly :(

a = ["a", "b", "c", "d"]
b = [1, 0, 0, 1]

c = []
a.each_with_index do |e, i|
  c << e if b[i] == 1
end

#> ["a", "d"]

Refactorings

No refactoring yet !

B8ba61cc84ecb63c859435be28547dfb

steved

May 6, 2011, May 06, 2011 09:03, permalink

No rating. Login to rate!
a = ["a", "b", "c", "d"]
b = [1, 0, 0, 1]

c = a.zip(b).select { |e| e.last == 1 }.map(&:first)
puts c.inspect
#> ["a", "d"]
057e54d9a7b6ce3614413fcab825fca8

Stephen

May 6, 2011, May 06, 2011 09:48, permalink

No rating. Login to rate!

# @Fu86, I give you cred for this one. You pretty much guessed it right. Taking advantage of returned Enumerators adds a lot of capabilities...

a = ["a", "b", "c", "d"]
b = [1, 0, 0, 1]
c = a.reject.with_index { |e, i| b[i].to_i.zero? }

# => ["a", "d"]
Ee0505bbd355292778077fb662c88f13

Fu86

May 11, 2011, May 11, 2011 01:42, permalink

No rating. Login to rate!

Ah, great stuff! Thanks a lot, Stephen!

Your refactoring





Format Copy from initial code

or Cancel