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.

class

Last updated at Posted at 2020-12-02

hello_class.rb

概要

  • 引数がある場合 Hello (引数).
  • 引数がない場合 Hello World.

と出力するコードを作成する.

解法

前の 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
  • puts_hello は "Hello (name)" の出力
  • get_name で ARGV[0] に入っているかいないかを判断して name に代入

最終的なコードは以下の通りである.

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.capitalize
  end
end
Greeter.new

実行結果

> ruby hello_class.rb
Hello World.

> ruby hello_class.rb Masaki
Hello Masaki.

> ruby hello_class.rb masaki
Hello Masaki.

.capitalize は文字列先頭の文字を大文字に, 残りを小文字に変更した文字列を返す. だから masaki を ARGV[0] に入れても, Masaki となる.

参考ページ

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


  • source ~/grad_members_20f/members/djj31370/c6_class_hello.org
6
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
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?