ruby exercise memo VI (hello class)

Purpose

Let's actually write the code of ruby. This time is the VI bullet.

theme

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)

The code I wrote this time (hello \ _ class.rb)


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

Commentary

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.

Reference material

-ruby Exercise Memo II (variable and method) -Chart type ruby-VI (hello class)


Recommended Posts

ruby exercise memo VI (hello class)
[Self-use memo] (Ruby) class, class instance, instance
ruby exercise memo I (puts)
Ruby memo
ruby Exercise Memo II (variable and method)
Class in Ruby
[wip] Ruby memo
ruby basic syntax memo
11th :: ruby_VI (hello class)
Java memo (standard class) substring
Ruby study memo (conditional branching)
Write class inheritance in Ruby
Java memo (standard class) length
Personal memo Progate Ruby I (2)
Java learning memo (abstract class)
What are Ruby class methods?
Ruby study memo (recursive function)
Personal memo Progate Ruby I (1)
[Ruby] Class methods, instance methods, etc.
[Ruby ~ Iterative processing ~] Study memo 4
ruby Exercise Memo III (if, case, array, each by leap year)