6
2

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.

variable and method

Last updated at Posted at 2020-12-29

!Mac OS X-10.15.7 !ruby-2.7.1p83

変数(variable)

ruby の変数は型宣言 (C ならば int, char 等) が不要.

例えば, 変数への代入は

name = 'Rudy'

でできる.

例題

引数 ARGV[0] を引数 name に代入して

> ruby name_variable.rb Rudy
Hello Rudy.

と返す name_variable.rb を作成する.

まず, name に ARGV[0] を代入する#+beign_src rubyname = ARGV[0]#+end_srcそして, 出力させるために#+beign_src rubyputs "Hello #{name}."#+end_srcとすると

> ruby name_variable.rb Rudy
Hello Rudy.

と出力される.

method

Rubyでは関数 (function) は method を定義(definition)することになる.

methodは0個以上の引数(argument)を取ることができる.例えば

def hello(name)
  p name
end

例題

> ruby hello_method.rb Rudy
Hello Rudy.

と返す hello_method.rb を作成する.

まず, name に ARGV[0] を代入する.

name = ARGV[0]

次に hello メソッドを呼び出す

name = ARGV[0]
hello(name)

しかし, これでは hello メソッドが宣言されていないのでエラーがでる.だから, 引数1つの hello メソッドを作成する.

def hello(name)
  puts "Hello #{name}."
end
name = ARGV[0]
hello(name)

これで

> ruby hello_method.rb Rudy
Hello Rudy.

と出力される.

参考ページ

チャート式ruby-II(variable and method)


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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?