Hi --
Hi --
current_item is an instance of class CartItem, and increment_quantity is an instance method of CartItem. It doesn't matter what file you're in. The only thing that matters is whether or not the object (current_item) understands the message you're sending it (increment_quantity).
Hmm, isnt current_item a local variable? It makes sense that in this code the current_item.increment_quantity is wokring, but my questions how it is working. For me its essential to understand how it works so I know how to use in the future . I would like to understand what is going on in the background.
It's not even the background -- it's all up front
current_item is a local variable which happens to refer to a CartItem object. You want that CartItem object to do something, so you send it the message "increment_quantity". The message-sending syntax in Ruby takes the form:
object.message
where object can be, and usually is, a variable. "Sending a message" is how you tell the object you want it to execute a particular method (or trigger whatever unknown-method handlers it may have available to it).
The "local" in "local variable" describes its scope. Local variables inside method definitions are only in scope inside the definition:
x = 1 # x in outer local scope def my_method x = 2 # x in method's local scope puts x # prints 2 end puts x # back to first x, so it prints 1
But, even though they are local in scope, they can have anything assigned to them:
class C def report puts "I'm a C instance!" end end
def my_method x = C.new x.report end
my_method # I'm a C instance!
I definitely agree that it's a good idea to get a good handle on Ruby
while you're learning Rails. There's even a book written exactly for
people who are trying to do exactly that
David
Nice explanation David, you're a helpful old chap. And your book is excellent. I was a beta reader and it was/is a tremendous resource to a Rails/Ruby developer
Good work mate
Keep it up
Kirk out
Hi --