Search code examples
rubyparametersargumentsblockproc

Passing a block as an argument


just playing with some random string generation and getting my knickers in a twist over how to pass an argument to a method which gets re-evaluated each time. Here's where i'm at with the code:

random_letter = ('a'..'z').to_a[rand(26)]

random_string = "".ljust(141, random_letter)

Of course the issue here is that random_letter only gets created once, then that same instance is used 141 times, I'm trying to get random_letter to be generated on each of the 141 occasions that "" is padded with random_letter.

I'm sure there are likely easier ways of ultimately achieving a 141 random char string and i'd be interested to see better suggestion too, howveer i would like to work out how to achieve this using that path that i chose above. Thanks


Solution

  • It is impossible to do that using ljust. All arguments are evaluated prior to execution of the main method. Whatever code you insert in the second argument position of ljust, that will be evaluated into a certain object, and that single object will be used in ljust.

    One way to do what you want is:

    26.times.with_object(""){|_, s| s << [*"a".."z"][rand(26)]}
    #=> "zjqmdumyrmmfnwsdjysvtolxjn"