Home > front end >  A method that takes any number of args, return new hash if args are key of hash, original hash if no
A method that takes any number of args, return new hash if args are key of hash, original hash if no

Time:12-06

describe hash_selector,

should accept a hash and any number of additional arguments"
should return a new hash containing keys of the original hash that were passed in as additional arguments
when no additional arguments are passed return the original hash
def hash_selector(hash, *args)
   
    new_hash = {}
     args.each do |arg| 
        if hash.has_key?(arg)
           new_hash[arg] = hash[arg]
        end
    end

 new_hash
end

i have done this and it returns the new_hash, but i cant figure out how to write it so it returns the original hash when no args passed PLEASE HELP!!

CodePudding user response:

I would just add this as the first line of the method:

return hash if args.empty?

CodePudding user response:

Add the following line inside the function at the beginning.

return hash if args.empty?

CodePudding user response:

I understand that this may be a homework excersize but its a very overcomplicated and non-rubyeske way of doing what Hash#slice does in a single method call.

def hash_selector(hash, *args)
  args.any? ? hash.slice(*args) : hash
end

This is shorthand for:

def hash_selector(hash, *args)
  if args.any? 
    hash.slice(*args)
  else
    hash
  end
end
  • Related