I’m a total beginner at Ruby. I’m trying to read this code:
private
def find_cart
session[:cart] ||= Cart.new
end
I’m most comfortable with PHP code, so that biases how I read this. If
I had to guess, I’d say this is saying something like “Let’s create a
private method called find_cart. When called, this should check the
session array for a key called ‘cart’. If there is no key called ‘cart’
in the session array yet, then we create a new Cart object and store it
in the session array with a key of ‘cart’.”
How close did I get?
You’re spot on, except session is a Hash, not an Array.
Hi –
On Tue, 21 Nov 2006, Jake Barnes wrote:
I had to guess, I’d say this is saying something like “Let’s create a
private method called find_cart. When called, this should check the
session array for a key called ‘cart’. If there is no key called ‘cart’
in the session array yet, then we create a new Cart object and store it
in the session array with a key of ‘cart’.”
How close did I get?
Very, but the key is the symbol :cart, rather than the string
‘cart’… and the only reason that doesn’t matter is that Rails
performs some modifications on the Hash class so that symbols and
strings can be used interchangeably as keys. In un-modified Ruby
code, :cart and “cart” are completely different hash keys.
David
–
David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
Hi Jakob,
Jakob S. wrote:
check the session array for a key called ‘cart’.
You probably already know this, but just to make sure…
In Rails, session data is stored as a hash, not an array.
Best regards,
Bill
On Nov 22, 2006, at 00:03 , Jake Barnes wrote:
‘cart’
in the session array yet, then we create a new Cart object and
store it
in the session array with a key of ‘cart’."
How close did I get?
Bingo, good job. That’s pretty much exactly what happens.
–
Jakob S. - http://mentalized.net