Ruby体験記8 〜ハッシュ
どうも。三十路です。
今日も元気よくこの本でお勉強です。
プログラミング学習シリーズ Ruby 1 はじめてのプログラミング
- 作者: arton,宇野るいも
- 出版社/メーカー: 翔泳社
- 発売日: 2009/01/29
- メディア: 大型本
- 購入: 5人 クリック: 95回
- この商品を含むブログ (30件) を見る
ハッシュ
配列と同様にデータの管理する型。ハッシュはキーで管理する。
animals = {} animals["犬"] = "わんわん" animals["猫"] = "ニャーニャー" animals["牛"] = "モーモー" puts animals["犬"] puts animals["猫"] puts animals["牛"]
キーと値を => でつなぐこともできます。
animals = { "犬"=>"わんわん", "猫"=>"ニャーニャー", "牛"=>"モーモー" } puts animals["犬"] puts animals["猫"] puts animals["牛"]
練習問題
#7.1
def delete_multiple array, current, max a = current while a <= max array[a] = nil a += current end end def last_number array i = -1 while !array[i] i -= 1 end array[i] end MAX=100 puts "上限値は#{MAX}です" nums = [] for i in 0..MAX nums << i end primes = [] for i in 2..MAX if nums[i] primes << i delete_multiple(nums, i, MAX) if i * i > last_number(nums) break end end end for i in 2..MAX if nums[i] primes << nums[i] end end puts "#{MAX}までの素数は#{primes}"
#7.2
PAPER=0 SCISORS=1 STONE=2 WIN={ [PAPER, STONE] => true, [SCISORS, PAPER]=>true, [STONE, SCISORS]=>true } HANDS={PAPER=>"パー",SCISORS=>"チョキ",STONE=>"グー"} com_win=0 plr_win=0 while com_win < 3 && plr_win < 3 puts "パーは0、チョキは1、グーは2?" #choice = gets() choice = rand(3) player = Integer(choice) computer = rand(3) puts "あなた:#{HANDS[player]}, コンピューター:#{HANDS[computer]}" if WIN[[player, computer]] plr_win += 1 elsif WIN[[computer, player]] com_win += 1 else puts "あいこ" end end if plr_win >=3 puts "あなたの勝ち" else puts "あなたの負け" end
そんな日。