jbk
jbk

Reputation: 2200

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

Upvotes: 0

Views: 66

Answers (2)

Surya
Surya

Reputation: 16022

As sawa has already pointed out that it can't be done the way you're trying to do it, however there are other ways to do it with a slight modification in your code:

random_letter = proc { [*'a'..'z'].sample }
random_string = 141.times.with_object(''){ |_, s| s << ''.ljust(1, random_letter.call) }
p random_string
# => "cnvmixiolqsgtdbdjrjsmaulslyphvcmvxnheulnrsxdqqryqgrplenyyneagufglkxqsyowbcfdgejwafrubqfnkvnehdtkhygmtpizbgzkyboyqhlrxqdzhglnsigtaglviaesphois"

or

random_string = 141.times.with_object(''){ |_, s| s << ''.ljust(1, [*'a'..'z'].sample) }
p random_string
# => "wcgkqliwyggfyvxfblyalqgpdbrqvlikxuqwyecihvdkytsbsikhwldvsjamkiicytfcgvvmoeuleeftzizrscujejkuanrxbqwzcywtboidrftinayfvqdygqwrfjhxvyiazzxinjudm"

Upvotes: 0

sawa
sawa

Reputation: 168269

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"

Upvotes: 1

Related Questions