Mikey Hogarth
Mikey Hogarth

Reputation: 4702

Active Record syntax explanation - beginner

I'm working on learning ruby/rails at the moment - The book i'm reading has had a tendency to skip over bits of new syntax. In particular, this bit;

person = Person.find(:first, :conditions => ["name = ?", "Mikey"])

From what I can tell this method takes a symbol as its first argument and what looks like a one-item hash with a symbol/array key/value. Is this correct and if so, why am I suddenly able to specify a hash without curly braces { } in this context?

Upvotes: 1

Views: 217

Answers (1)

Jacob Mattison
Jacob Mattison

Reputation: 51062

In Ruby method parameters, any key=>value pairs that are placed after normal arguments, but before a block, are bundled into a single hash. So if you called

my_method("hello", :something=>"yo!", :another_thing=>"bah!")

that means that my_method is being passed two arguments, a string ("hello"), and a hash ({:something=>"yo!", :another_thing=>"bah!"}).

Among other reasons, this prevents confusion between curly braces indicating a hash parameter, and curly braces indicating a block. It also makes a convenient way to simulate "named parameters", which otherwise don't exist in Ruby.

Upvotes: 4

Related Questions