LoginSignup
0
0

More than 5 years have passed since last update.

34日目 Rubyのメソッドの使い方

Posted at

三日坊主にならないように・・・!
今日はProgateでRubyのメソッドの使い方を学びました。

Ruby Ⅰ 復習

変数、if文、条件式
ほとんど手間取らなくなったけど、何個かひっかかった(12分)

Ruby Ⅱ 復習

配列、each、if
ちょっと手間取って(18分)

Ruby Ⅲ メソッドの使い方

def-endで囲む

def aaa
    puts "aaa"
end 

で囲むとその間にかいたプログラムを呼び出せる

def aaa(name)で引数を渡せる

def aaa(name)
    puts "#{name}"
end 

aaa("test")

def aaa(name,price)で複数の引数を渡せる

returnで戻り値を使う

def sum(a,b)
    return a + b
end 
aaa = sum(1,2)
puts aaa

defに条件をつける

こういう使い方でできるって面白い。

def aaa?(num)
  return num >= 1000
end

if aaa?(3000)
    puts "1000 over"
else
    puts "1000 under"
end

defの中で条件を使う

returnにかかると以降の処理が行われない。
defの中でifを作って、ifにかかる場合とかからない場合で処理を分ける
好みもありそうだけど、こっちの方が読みやすいかも?

def aaa(num)
    if num >= 1000
      return price
    end

    return num + 500
end

キーワード引数

プログラムのどこに何の引数を渡すかわかりやすくできる。

def buy(item:, price:, count:)
    puts "#{item}を#{count}台のお買い上げです"
    puts "合計金額は#{price * count}円です"
end
# キーワード引数を使うように書き換えてください

buy(item:"テレビ", price:15000, count:2)

puts aaa(5000)

完成!

(所要時間45分)

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