cresjoy - 8 months ago 22

Ruby Question

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`

`@result`

`a*b`

`@`

`@`

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 : )