Hi,
I want to split an array depending on the evaluation of a code-block, like
this
a, b = [1,7,10,3,12].split do |x|
x < 10
end
# a = [1,7,3]
# b = [10,12]
I haven't found a function like this (Ruby 1.6.6). Have I missed it?
When trying to implement it, I also found, that there is no Delete_if (it
exists, but does what Delete_if! should be doing). I came up with the
following, can anybody help me, which implementation to use (performance?):
def split1(aArray)
a = aArray.dup.delete_if do |x|
not yield x
end
aArray.delete_if do |x|
yield x
end
[a, aArray]
end
def split2(aArray)
a = aArray.dup.delete_if do |x|
not yield x
end
[a, aArray - a]
end
def split3(aArray)
a = []
b = []
aArray.each do |x|
if yield x then
a.push x
else
b.push x
end
end
[a, b]
end
[method(:split1), method(:split2), method(:split3)].each do |split|
a,b = split.call([1,7,10,3,12]) do |x|
x < 10
end
p split
puts "Here goes a: #{a.inspect}"
puts "Here goes b: #{b.inspect}"
end