Charles - 1 year ago 32

Ruby Question

I want to make a random number generator. The number results were

`180, 91, 300`

`"Your results are: 7, 7, 7"`

`7`

`7`

`random = 3.times.map {Random.new.rand(0..10000)}`

puts random #Results ====> 180, 91, 300

@duh={}

random.map {|x|

case x

when 1..3000

@duh["7"]=10000 #Jackpot

when 3001..6000

@duh["Cherries"]=500

when 6001..10000

@duh["Diamond"]=400

end

}

puts "Your results are: #{@duh.keys.join(", ")}!"

Answer

You're using `map`

here, but not in the right way:

```
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(", ")}!"
```

The only reason to use `map`

is if you're interested in the results of that operation. Otherwise use `each`

which is faster since it doesn't care about the result of each iteration.

Remember that in a Hash you can have a given key only once. Assigning the same value to `7`

over and over means there is only one 7 key.

Source (Stackoverflow)