LoginSignup
0
0

More than 1 year has passed since last update.

3/25 Ruby入門remained 基礎文法編

Posted at

個人的リマインド用

ifで条件分岐

ユーザーから値を受け取る gets

gets.to_i

if score > 80
    puts "great!"
elsif score > 60
    puts "good"
else
    puts "so so"
end

/*簡単な条件分岐は puts "great!" if score > 80で代替可能

caseで条件分岐

getsは最後に改行コードがついているので.chompで取り除く

case signal
when "red"
    puts "stop"
when "green", "blue"
    puts "go"
when "yellow"
    puts "caution"
else
    puts "wrong signal"
end

timesで繰り返し

10.times do | i | /*1行しかない時はdo,endを{}で代替可能*/
    puts "#{i}: Hello"
End

forとeachで繰り返し

for i in 15 .. 20 do /*省略可*/
    p i /*15 ~ 20が1つずつ入っていくる*/
end

for color in ["red", "blue"] do /*省略可*/
    p color
end

for name, score in {taguchi: 20, sato: 40} do /*省略可*/
    p "#{name}: #{score}"
end

/*eachで書き換え可能*/
{Taguchi:20, sato:40}.each do |name, score|
    p "#{name}: #{score}"
end

loapでずっと繰り返し

ctrl+Cで止められる

i = 0
loap do
    p i
    i += 1
end

break(途中で止める), next(1つスキップ)

10.times do | i |
    if i == 7
        break or next
    end
    p i
end

method

def sayHi(name = "tom(default)") 
    puts "hi! #{name}"
    /*値を返す時はreturn(returnなくても最後に読み込んだ値は返す)*/
end

sayHi("tanaka") /*()は省略可*/
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