我想找出第一个,第二个和第三个结果是什么,以便我可以if firstnumber==secondnumber && secondnumber==thirdnumber
。我怎么能在结果上找到这些数字?
numbers = 3.times.map { Random.new.rand(0..10000) }
prizes = numbers.map do |x|
case x
when 1..3000
[ '7', 10000 ]
when 3001..6000
[ "Cherries", 500 ]
when 6001..10000
[ "Diamond", 400 ]
end
end
puts "Your results are: #{prizes.collect { |p| p[0] }.join(", ")}!
我尝试使用p [0] [0],但它改为给出第一个字母。
答案 0 :(得分:2)
说是否:
results = prizes.collect { |p| p[0] } #=> ["Diamond", "Cherries", "7"]
然后执行以下操作以获得每个结果:
results[0] #=> "Diamond"
results[1] #=> "Cherries"
results[2] #=> "7"
您还可以使用results.first
来获取第一个元素。如果您正好在Rails中工作,您甚至可以执行以下操作:
results.second #=> "Cherries"
results.third #=> "7"
答案 1 :(得分:1)
这是一个很好的方法:
numbers = 3.times.map { Random.new.rand(0..10000) }
prizes = numbers.map do |x|
case x
when 1..3000
{ name: '7', val: 10000 }
when 3001..6000
{name: "Cherries", val: 10000 }
when 6001..10000
{name: "Diamond", val: 400 }
end
end
# You could replace 'map' with 'collect' here and have the same results
prizes_string = prizes.map { |p| "#{p[:name]}: #{p[:val]}" }.join(" and ")
puts "Your results are: #{prizes_string}!"