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
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.
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.
It’s a little unclear from this which part of the procedure you want to
parameterize, but my guess is that you’d do this:
class Array
def indexes_of(value = nil)
value = yield(self) if block_given?
self.empty? ? ‘The array is empty.’ : hash_of_indexes[value.to_f]
end
end
Then you’d call it on an array with a value or a block:
To explain, you have a block – { |x| x > 5 } – that returns true or
false.
Inside your method, you call the block with the current element using
yield(e) to determine whether to add the current index to the list.
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
Use send, as in:
class Array
def indexes_of(function)
self.empty? ? ‘The array is empty.’ :
hash_of_indexes[self.send(function)]
end
end