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

Rubyの変数とMethod

Last updated at Posted at 2020-12-24

!Mac OS X-10.15.7 !ruby-2.7.1p83

変数

Pythonと似てて、Rubyは型宣言をする必要がない
受けとった引数ARGV[0]を適当な変数に代入して出力せよ

name = ARGV[0]
puts name

実行結果

$ ruby name.rb Rudy
Rudy

変数を使って足し算してみる

num = ARGV[0].to_i
sum = num + num
puts sum

実行結果

$ ruby name.rb 1
2

Method

関数などのまとまりはmethodを定義することになる
これもPythonの関数定義と少し似ている

def メソッド名 (引数1, 引数2)
  処理1
  処理2
    
    
end

例えば

def name(str1,str2)
    puts "#{str1} #{str2}"
end

word1 = "hello"
word2 = "world"
name(word1,word2)

実行結果

$ ruby def.rb
hello world

ARGV[0]を代入させ、キーボードから文字を受け取りたかったら

def name(str1,str2)
    puts "#{str1} #{str2}."
end

word1 = ARGV[0]
word2 = ARGV[1]
name(word1,word2)

実行結果

$ ruby def.rb hello world
hello world.

参考記事

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


  • source ~/grad_members_20f/members/wjswnsrud12/memo6.org
4
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
4
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?