Let's actually write the code of ruby. This time is the VI bullet.
Learn object-orientation and improve hello \ _method.rb. (Hello \ _method.rb is code written here [https://qiita.com/gagagagazelle/items/a09eeb60c9e7913ea860)) The key ideas are as follows.
--Capsulation --Inheritance --Polymorphism
(Issues at https://qiita.com/daddygongon/items/969ad5112878f6dab844)
class Greeter
attr_accessor :name
def initialize(name='world')
@name = name
end
def hello
puts "Hello #{@name}."
end
end
if $PROGRAM_NAME == __FILE__
greeter = Greeter.new()
greeter.hello
greeter.name = ARGV[0]
greeter.hello
end
The way the class is written is not unusual.
However, I didn't know how to write attr_accessor: name
.
attr_accessor
attr_accessor
seems to behave equivalently to: (see here)
def name # reader(getter)
return @name
end
def name=(new_name) # writer(setter)
@name = new_name
end
I see. I'm going to use it from now on.
-ruby Exercise Memo II (variable and method) -Chart type ruby-VI (hello class)
Recommended Posts