(*I am a beginner who has been studying programming for about a month.)
Thank you for looking at the question.
While studying a Ruby introductory book, I have some questions.
The Ruby version is ruby 2.6.5.
Here are the codes you may not know:
class Product
attr_reader:name, :price
default initialize (name, price)
@name = name
@price=price
end
def to_s
"name:#{name}, price:#{price}"
end
end
product=Product.new('A great movie', 1000)
product.to_s#=>"name:A great movie, price:1000"
The above code is in the chapter where inheritance is described.
I understand that the Product method overrides the to_s method.
However,
in the to_s method
"name:#{name}, price:#{price}"
So why is the argument name, price?Isn't it @name, @price?
I looked into various things, but I didn't know.
Thank you for your cooperation.
attr_reader:name,:price
A method called name, price is added to
Default reads the value of the variable with @
In other words,
attr_reader:name
is
def name
return@name
end
It will be the same as
So you can get the value without @
By the way, I think I use attr_accessor more often, but it also comes with a setter, so
def name=(val)
@name=val
end
It also comes with
© 2024 OneMinuteCode. All rights reserved.