Forum: Ruby passing hash as arguments

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jason L. (Guest)
on 2009-01-27 08:24
Is this the best way (though contrived) to use a hash as an argument in
ruby?

def state_name_age(feeling, info{})
  "#{:name} is #{feeling} #{:age} #{:units} old"
end

my_info = {}
my_info = {:name => "Kate", :units => "years", :age => 24}

irb(main):018:0> state_name_age('happily', my_info)
=> "Kate is happily 24 years old"

then...

irb(main):068:0> state_name_age 'happily'
=> " is happily   old!"

This seems to be the way Rails has things set up to pass optional
arguments... Is that correct?
Tom L. (Guest)
on 2009-01-27 08:33
(Received via mailing list)
> def state_name_age(feeling, info{})
>   "#{:name} is #{feeling} #{:age} #{:units} old"
> end

Try:

def state_name_age(feeling, info={})
   "#{info[:name]} is #{info[feeling]} #{info[:age]} #{info[:units]}
old"
end

irb(main):018:0> state_name_age('happily', :name => "Kate", :units =>
"years", :age => 24)
Philip D. (Guest)
on 2013-11-20 06:36
Tom L. wrote in post #773986:
>> def state_name_age(feeling, info{})
>>   "#{:name} is #{feeling} #{:age} #{:units} old"
>> end
>
> Try:
>
> def state_name_age(feeling, info={})
>    "#{info[:name]} is #{info[feeling]} #{info[:age]} #{info[:units]}
> old"
> end
>
> irb(main):018:0> state_name_age('happily', :name => "Kate", :units =>
> "years", :age => 24)

Is there anyway to pass the hash without having to "expand" it as you
did. Similar to:

## Make the hash
options = {:option1 => "hello", :option2 => "cats"}
## Call the function
my_function(options)

Would that work?
tamouse m. (Guest)
on 2013-11-21 11:00
(Received via mailing list)
On Nov 19, 2013, at 8:36 PM, Philip D. <removed_email_address@domain.invalid> 
wrote:

>> end
> my_function(options)
>
> Would that work?
>
>


Try It And See.
This topic is locked and can not be replied to.