ifやループ構文。 Rubyの真髄と言われるブロック構文のまとめ公開
ruby
# if
a = 0
if a == 0
p "true"
elsif hoge
p "elseif"
elsif
p "false"
end
#if修飾子
"ok" if 10 < 20 # => "ok"
"ok" if 20 < 20 # => nil
#三項演算子
6%2 == 0 ? "even" : "odd" # => "even"
7%2 == 0 ? "even" : "odd" # => "odd"
# unless
a = 0
unless a
p "false"
else
p "true"
end
# while
i = 0
while i < 10
p i
i +=1
end
# while 2
i = 0
p(i+=1) while i < 10
# until
i =0
until i > 10
p i
i +=1
end
# for
for x in [1,2,3]
p x
end
#each
[11,12,13].each do |x|
p x
end
#ループ制御 redo 用途が思いつかないスルー
#ループ制御 Kernel#catch Kernel#throw
catch(:exit) do
for x in [[1,2],[3,4]]
for j in x
throw :exit if j == 3 # 3の時にループ終了
p j
end
end
end
#ブロックの使用 each
squares = []
[1,2,3].each { |x| squares << x*x}
squares #=> [1, 4, 9]
#ブロックの使用 map
[1,2,3].map { |x| x*x} #=> [1, 4, 9]
#ブロックの使用 each 条件
squares = []
[1,2,3,4].each { |x| squares << x if x%2 == 0}
squares #=> [2, 4]
#ブロックの使用 select
[1,2,3,4,5].select { |x| x%2 ==0 } #=> [2, 4]
#ブロックの使用 each_with_index
[[1,2],[3,4]].each_with_index{|(x,y),i| puts "i = #{i} / x = #{x} ,y = #{y}}"}
コメントする