0
0

More than 3 years have passed since last update.

ruby メソッドの作り方

Last updated at Posted at 2019-11-01

ドットインストール(https://dotinstall.com/)を見て
自分なりにまとめたものです。

メソッド

def  sayHello
    puts "Hello word!!"
end

sayHello

実行結果:Hello word!!
 

  • メソッドを呼び出すときはメソッド名書くだけで呼びだせる
def  sayHello(name)
    puts "Hello #{name}!!"
end

sayHello ("Angela") #()は省略可能
  • 引数を渡すことも出来る

実行結果:Hello Angela!!

def  sayHello(name = "Angela")
    puts "Hello #{name}!!"
end
# nameを渡されなかった時に"Angela"が渡される
sayHello 

  • 引数にデフォルト値も設定できる

実行結果:Hello Angela!!


def  sayHello(name = "Angela")
    return "Hello #{name}!!"
end

p sayHello
  • メソッドは最後に評価された値を返す
  • returnで返されたのは"Hello #{name}!!"  p で返されたものを表示している。

実行結果: "Hello Angela!!"

ローカル変数の話

  • whetherはローカル変数だからdef~endの中でしか使えない
def  sayHello(name = "Angela")
    weather = "sunny"
    return "Hello #{name}!!"
end

p sayHello
p weather

実行結果:エラー

0
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
0
0