Ruby基礎②
ハッシュ
Key/Valueで管理する 省略記法があるので、 以下の3パターンはどれも結果が同じになる
scores = {"tanaka" => 200, "suzuki" => 300} scores = {:tanaka => 200, :suzuki => 300} scores = {tanaka: 200, suzuki: 300}
出力
p scores[:suzuki]
値を書き換えることも可能
scores[:tanaka] = 500 p scores
p scores.size #要素数 p scores.keys #Key一覧を返す p scores.values #Value一覧を返す p scores.has_key?(:tanaka) #指定したKeyが存在するか真偽値を返却する
オブジェクトの変換
x = 50 y = "3" p x + y.to_i #int型への変換 p x + y.to_f #float型への変換 p x.to_s + y #String型への変換 score = {tanaka: 200, suzuki: 500} p scores.to_a.to_h #配列/ハッシュへの変換
%記法
#ダブルクォーテーションを出力すためにバックスラッシュが必要 puts "he\"llo" puts 'he\'llo' #%記法を使用するとストレートに記述することができる #%Q、%...ダブルクォーテーションで括った場合と同じ。Qは省略可能 #%q...シングルクォーテーションで括った場合と同じ puts %Q(he"llo) puts %(he"llo) puts %q(he'llo)
配列にも使用可能。 その場合は%W,%wを使用する
p ["red","blue"] p ['red','blue'] p %W(red blue) p %w(red blue)
書式付きで文字列を埋め込む
p "name: %s" % "tanaka" #桁数指定 p "name: %10s" % "tanaka" #結果=> "name: tanaka" #桁数指定+左寄せ p "name: %-10s" % "tanaka" #結果=> "name:tanaka " p "id: %05d, rate: %10.2f" % [123, 1.567] #結果=> "id:00123, rate: 1.57" #printf sprintfでも使える printf("name: %10s\n","tanaka") printf("id: %05d, rate: %10.2f\n" ,123, 1.567) p sprintf("name: %10s\n","tanaka") p sprintf("id: %05d, rate: %10.2f\n" ,123, 1.567)
if文
# > < >= <= == != # &&(AND) ||(OR) !(NOT) score = gets.to_i if score > 80 then puts "great!" elsif score > 60 then puts "good!" else puts "so so..." end
thenは省略可能
# > < >= <= == != # &&(AND) ||(OR) !(NOT) score = gets.to_i #ユーザから入力された値を使用 if score > 80 puts "great!" elsif score > 60 puts "good!" else puts "so so..." end
条件が1つの場合は以下のようにも書ける
puts "great!!" if score >= 85
case文
#.chomp(改行を削除) signal = gets.chomp case signal when "red" then puts "stop!" when "green","blue" then puts "go!" when "yellow" then puts "caution!" else puts "wrong signal" end
こちらもthenを省略可能
#.chomp(改行を削除) signal = gets.chomp case signal when "red" puts "stop!" when "green","blue" puts "go!" when "yellow" puts "caution!" else puts "wrong signal" end