pigusan pigusan - 1 year ago 105
Ruby Question

Why does the function not work when using splat in the parameter

When you remove the * splat from the parameter the function works fine. However when it's in there the function does not work. Why? See my repl (https://repl.it/LuY8/4)

class Hash
def keys_of(*arguments)
new_array = []
self.each do |key, value|
#puts arguments
#puts key
if value == arguments
new_array << key
end
end
new_array
end
end

animals = {"sugar glider"=>"Australia","aye-aye"=> "Madagascar","red-footed tortoise"=>"Panama","kangaroo"=> "Australia","tomato frog"=>"Madagascar","koala"=>"Australia"}

animals.keys_of('Madagascar')

Answer Source

That's a varargs method signature, that is arguments will always be an array, even for singular values. That means you're getting ['Madagascar'] as your arguments and since your keys aren't arrays of a single string, your match fails.

What you probably want is to invert the whole routine and make it more Ruby-like by doing this:

def keys_of(*arguments)
  each_with_object([ ]) do |(key, value), a|
    a << key if (arguments.include?(value))
  end
end

Problem solved. Ruby has a very rich and featureful core library and Enumerable is the real jewel. Familiarize yourself with what it can do before writing your own work-alike methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download