Skip to content

Instantly share code, notes, and snippets.

@sonkm3
Last active December 20, 2015 13:19
Show Gist options
  • Save sonkm3/6137749 to your computer and use it in GitHub Desktop.
Save sonkm3/6137749 to your computer and use it in GitHub Desktop.
ruby: problem on get random number with specific digit. and found reason(Confusing Range object and Array object)
# this does not works. map called once.
p [1..10].map{|i|rand(9)}.join('')
# > "1"
# this works.
p [*1..10].map{|i|rand(9)}.join('')
# > "5012242033"
# difference is [*1..10] and [1..10]
# "*" expands Range object to list, but both are "Array" Class. strange...
p [1..10]
p [*1..10]
# > [1..10]
# > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# both of them are Array, but there are diffrence
# [1..10] is Array contained with single Range object(1..10).
# [*1..10] is Array contained with 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
# this is why
p [1..10].map{|i|rand(9)}.join('')
# does not work as I expected.
# Found more easier solution. use bare Range object.
p (1..10).map{|i|rand(9)}.join('')
# > "5751656133"
@kosugi
Copy link

kosugi commented Aug 12, 2013

BTW, how about 10.times.map {rand(9)}.join # and I think rand(10) is suitable in this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment