Comments on: Random Numbers and Strings in Ruby http://www.blackbytes.info/2015/03/ruby-random/ Ruby Programming Tutorials Thu, 22 Sep 2016 15:35:14 +0000 hourly 1 http://wordpress.org/?v=4.3.6 By: Panagiotis Atmatzidis http://www.blackbytes.info/2015/03/ruby-random/#comment-393 Fri, 24 Jul 2015 10:29:17 +0000 http://www.blackbytes.info/?p=1599#comment-393 o = [('a'..'z'), ('A'..'Z')].map { |i| i.to_a }.flatten
string = (0...50).map { o[rand(o.length)] }.join

From Stack Overflow works fine.

I used a variant in one of my scripts works awesomely well and it’s fast. That said, it’s way better to write code you and others can understand on the fly in production mode, than smart-ass long snippets copy-pasted from SO.

I think creating a method (like a black box) is the way to go.

]]>
By: Jesus Castello http://www.blackbytes.info/2015/03/ruby-random/#comment-361 Sat, 21 Mar 2015 14:04:38 +0000 http://www.blackbytes.info/?p=1599#comment-361 You are right! Thanks for letting us know :)

For reference, this is what the documentation has to say about sample:

The elements are chosen by using random and unique indices into the array in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements.

In fact, if you do this:
charset = [*'a'..'z', *'A'..'Z'].sample(100).join.size

You only get 52 (one for each in the character set), which might not be what you want.

]]>
By: srcv http://www.blackbytes.info/2015/03/ruby-random/#comment-359 Sat, 21 Mar 2015 08:34:43 +0000 http://www.blackbytes.info/?p=1599#comment-359 This is not true actually. sample with arguments generates sample without repetitions, so it’s totally different from the original code!

]]>
By: Dewayne VanHoozer (@MadBomber) http://www.blackbytes.info/2015/03/ruby-random/#comment-358 Fri, 20 Mar 2015 16:42:03 +0000 http://www.blackbytes.info/?p=1599#comment-358 One of the many things I like about Ruby is how it seems every day I get a chance to learn something new about the language. I had never seen that splat do on a range before.

The other thing I learned today is that coping code that has smart quotes in it gets a syntax error.

]]>
By: Jesus Castello http://www.blackbytes.info/2015/03/ruby-random/#comment-356 Thu, 19 Mar 2015 16:11:08 +0000 http://www.blackbytes.info/?p=1599#comment-356 Thank you, I didn’t know that you can pass an argument to sample. And I agree that you should only generate the charset once if you are going to use the method multiple times, but I didn’t want to make the code more complex for the examples.

]]>