Skip to content

Instantly share code, notes, and snippets.

@thash
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save thash/9d7b7468c4b257b4b852 to your computer and use it in GitHub Desktop.

Select an option

Save thash/9d7b7468c4b257b4b852 to your computer and use it in GitHub Desktop.
AllAbout 023 Conditions
def judge(cond)
if cond
puts 'TRUE!!'
else
puts 'FALSE!!'
end
end
judge(0) #=> TRUE!!
judge(999) #=> TRUE!!
judge('hoge') #=> TRUE!!
judge('') #=> TRUE!!
judge([]) #=> TRUE!!
judge(true) #=> TRUE!!
judge(false) #=> FALSE!!
judge(nil) #=> FALSE!!
env = %w(production staging development invalid-value).sample(1).first
url = case env
when 'production' then 'http://api.hogehoge.com/'
when 'staging' then 'http://api.hogehoge-stg.com/'
when 'development' then 'http://api.local:3000/'
end
puts url
def checker(obj)
case obj
when String
'文字列です'
when Symbol
'シンボルです'
when Integer
'整数です'
else
'???'
end
end
puts checker('hogehoge') #=> 文字列です
puts checker(:hogehoge) #=> シンボルです
puts checker(nil) #=> ???
n = rand(1000)
puts "n = #{n}"
if (n > 500) then
puts 'big!'
end
# カッコとthenは省略可能で、ふつうはこう書きます。
if n > 500
puts 'big!'
end
if n.odd?
puts '奇数'
else
puts '偶数'
end
if n % 15 == 0
puts 'FizzBuzz'
elsif n % 3 == 0
puts 'Fizz'
elsif n % 5 == 0
puts 'Buzz'
end
case Time.now.hour
when 0...6
puts 'まだ寝ています'
when 6...12
puts '朝は眠い'
when 12...18
puts '昼寝の時間です'
when 18...24
puts 'そろそろ寝る時間です'
end
env = %w(production staging development invalid-value).sample(1).first
url = if env == 'production'
'http://api.hogehoge.com/'
elsif env == 'staging'
'http://api.hogehoge-stg.com/'
elsif env == 'development'
'http://api.local:3000/'
end
# どの条件にも該当しない時はurlにはnilが入る
puts url
n = rand(1000)
puts n.odd? ? '奇数' : '偶数'
def go_home
unless tired?
jog
end
if adult?
drink_a_beer
end
sleep
end
# 後置表記を使うとこうなる
def go_home
jog unless tired?
drink_a_beer if adult?
sleep
end
n = rand(1000)
n.odd? ? (puts '奇数') : (puts '偶数')
n = rand(1000)
n % 15 == 0 ? 'FizzBuzz' : (n % 5 == 0 ? 'Fizz' : (n % 3 == 0 ? 'Buzz' : nil))
unless user.blacklisted?
puts '処理を実行'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment