Ruby体験記8 〜ハッシュ

どうも。三十路です。

今日も元気よくこの本でお勉強です。

プログラミング学習シリーズ Ruby 1 はじめてのプログラミング

プログラミング学習シリーズ Ruby 1 はじめてのプログラミング

ハッシュ

配列と同様にデータの管理する型。ハッシュはキーで管理する。

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

そんな日。