Ruby: Passing parameters into new

There are a bunch of ways:

@adam = Person.new :id => 14, :name => ‘Adam’

Other ways of doing the right hand side of the expression are:

Person.new(:id => 14, :name => ‘Adam’) 

Or you can use:

Person.new id: 14, name: ‘Adam’

 

Person.new(id: 14, name: ‘Adam’) 

Person.new({id: 14, name: ‘Adam’})

Note however that:

Person.new (:id => 14, :name => ‘Adam’) 

(i.e. with a space after .new) won’t work giving you a:

SyntaxError: unexpected =>, expecting ‘)’

also, just:

(:id => 14, :name => ‘Adam’) 

by itself results in a syntax error.

Leave a Reply

Your email address will not be published. Required fields are marked *