C言語と違うところ2
- 配列
irb(main):019:0> ary1 = [3, d-3.0, "orange"] => [3, 4.0, "orange"] irb(main):020:0> ary1[0] => 3 irb(main):021:0> ary1[0..2] => [3, 4.0, "orange"]
配列は[]の中にオブジェクトを並べて定義する。
irb(main):023:0> ary1[-1] => "orange" irb(main):024:0> ary1[-2] => 4.0 irb(main):026:0> ary2 = [a, ary1] => [2, [3, 4.0, "orange"]] irb(main):027:0> ary2[1][2] => "orange"
配列の添え字が負の数の場合は配列を後ろから見た結果。
配列の中に配列を入れられる。
- for文
for i in 1..5 print(i,"\n") #"puts i"も同じ end
- if文
a = 2 if a == 0 puts "a is zero." elsif a < 0 puts "a is negative." else puts "a = #{a}" #"#{a}"はaの値参照 end # 実行結果 # a = 2
- if修飾子
whileにもwhile修飾子がある。
s = "me" puts "too short." if s.size < 4 #後付けif文 # 実行結果 # too short
- case文
switch的な。
score = 35 case score when 0..49 # 0以上49以下 puts "failure" when 50..79 # 50以上79以下 puts "pass" else # 80以上 puts "excellent" end # 実行結果 # failure
- next
for i in 1..10 # next はループ条件式直前にジャンプ next if i==5 puts i end # 実行結果 # 1 # 2 # 3 # 4 # 6 # 7 # 8 # 9 # 10
5だけジャンプされた。
ちなみに、redoを使うと、直前(ひとつ上)にジャンプ。