Hi,
I am trying to figure out how to pass a method call into a method.
I wrote a generic method that call be called on an array of numbers, and returns an array of the index values in the receiver that meet a specified condition:
class Array
def hash_of_indexes
if self.empty?
'The array is empty.'
else
h = {}
self.each_with_index { |e, i| h.include?(e.to_f) ? h[e.to_f] << i : h[e.to_f] = [i] }
h
end
end
def indexes_of
self.empty? ? 'The array is empty.' : hash_of_indexes[self.min]
end
end
puts [1, -100, -200.0, 1000000000000.12, 3, 1, -100, -100, -200].indexes_of.inspect # --> returns [2, 8]
What I'd like to do is to be able to specify what the condition is when calling the array, but can't get that to work right. I tried using yield inside of the square brackets in place of self.min above, and then calling the method with a block with self.min inside the block, but this results in an error (undefined method `min' for main:Object (NoMethodError)).
I have a feeling that I might need to use a lambda or proc to get this to work correctly, but am not sure about the syntax for either of those.
Any help would be appreciated.
Thanks,
Glenn