cresjoy cresjoy - 5 months ago 7
Ruby Question

Inquiry about some features of classes in ruby

im new to ruby and currently reading a book. After reading the section i made my own example and still a bit confused

class Operation
def multiply(a,b)
@result = a*b
end
def get_multiply
return @result
end
def divide(a,b)
@dividend = a / b
return dividend
end
end

my_operation = Operation.new
my_operation.multiply(5,6)
puts my_operation.get_multiply


Is there any difference between my code and simply scrapping the
get_multiply
method and return
@result
after we set it to
a*b
. Also if I take out the
@
sign on result my code still works. In the book it says this is an instance variable. My question is, whats the point of
@
really?

This code here still works

class Operation
def multiply(a,b)
result = a*b
end
def get_multiply
return result
end
def divide(a,b)
@dividend = a / b
return dividend
end
end

my_operation = Operation.new
puts my_operation.multiply(5,6)

Answer

@ symbol is used to persist the variable for later use. From this examples, it's' difficult to understand the importance of it. There is also @@ symbol for class variable - but I won't go in that for now.

In your code multiply method is playing the role of storing (probably for later use) and get_multiply is used to retrieve what was stored.

If you scrape get_multiply and use multiply directly - fair enough. Things will work. But you will now not have option to do some computation early, store it and retrieve it directly when required.

Hope it has helps : )

Comments