Last active
December 20, 2015 13:19
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BTW, how about 10.times.map {rand(9)}.join # and I think rand(10) is suitable in this case.