6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

マルチスケールシミュレーション特論:第11回(class)

Last updated at Posted at 2020-12-30

はじめに

今回は以下のhello.rbと同じ動作をするclassを作る

hello.rb
def puts_hello name
  puts "Hello #{name}."
end

def gets_name
  name = ARGV[0] || 'world'
  return name
end

name = gets_name
puts_hello name

クラスを作る

class_Greeter.rb
class Greeter
  def initialize
    @name = gets_name
    puts_hello
  end

  def puts_hello
    puts "Hello #{@name}."
  end

  def gets_name
    name = ARGV[0] || 'world'
    return name
  end
end

Greeter.new

@nameのように変数の頭に@を付けるとインスタンス変数として扱われる.initializeメソッドはコンストラクタ.

クラスの継承

Stringクラスを継承してGreeter_inheritedクラスを作る.

class_Greeter.rb
class Greeter_inherited < String
  def hello
    "Hello #{self}."
  end
end

greeter_inherited = Greeter_inherited.new(ARGV[0])
puts greeter_inherited.hello.green

メソッドの追加

Stringクラスにhelloメソッドを追加する.

class_Greeter.rb
class String
  def hello
    "Hello #{self}."
  end
end

puts ARGV[0].hello.red

参考文献

チャート式ruby-VI(hello class)


  • source ~/grad_members_20f/members/ryuta-kikuchi/qiita_articles/lecture11.org
6
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?