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 !
steved
May 6, 2011, May 06, 2011 09:03, permalink
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"]
Stephen
May 6, 2011, May 06, 2011 09:48, permalink
# @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"]
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 :(