Bohn
Bohn

Reputation: 26919

Understanding how parameters work in Ruby

Here is a sample code from a RSpec code:

describe Thing do
  def create_thing(options)
    thing = Thing.new
    thing.set_status(options[:status])
    thing
  end

  it "should do something when ok" do
    thing = create_thing(:status => 'ok')
    thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
    ...
  end
end

So my confusion is mostly on this line:

thing.set_status(options[:status])

So create_thing method has an "option" parameter then we are passing status part of that parameter? Can someone explain this syntax in some easier words?

Upvotes: 0

Views: 70

Answers (2)

Dave Newton
Dave Newton

Reputation: 160171

create_thing takes an argument called options.

Options is expected to be a hash (most likely).

You're passing the hash value with the key (a symbol):option to the set_status method.

You've passed an implicit hash to create_thing:

create_thing({ status: 'ok' }) is the same as
create_thing(status: 'ok') is the same as
create_thing(:status => 'ok')

Any way you call it, you access that value via options[:status].

Upvotes: 2

Leo Correa
Leo Correa

Reputation: 19789

options is just a variable. The part you need to understand is this part

thing = create_thing(:status => 'ok') 

You are basically passing a Hash to create_thing and therefore options is a hash. Then you can access the value of the status key by doing options[:status].

If the above mentioned line looked like this

thing = create_thing("Foo")

options would be "Foo" and you could get an error trying to do something like options[:status]

Upvotes: 3

Related Questions