1
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.

R11.org

Last updated at Posted at 2020-12-11

!Mac OS X-10.15.7 !ruby-2.7.1p83

第11回

チャート式Rubyの第6回目(最終)

classについて

hello_method.rb

def gets_name
  name = ARGV[0]
  if name == nil
    puts "What's your name?"
    name = gets.chomp
  end
  return name
end

def hello name
  puts "Hello, #{name}!!"
end

name = gets_name
hello name

以前作成したhello_method.rbを拡張しclass化してみる。

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変数に入力があれば、Hello {name}

入力がなければHello Worldを出力する。「main loopを消せないか」というのがclassの発想だそうだ。

参考サイト

チャート式ruby-Ⅵ


  • source ~/grad_members_20f/members/skona/memo/R11.org
1
0
1

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
1
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?