Forum: Ruby Novice programmer asking for help :P

Da6854bd6df963276d107bc968771ae7?d=identicon&s=25 Adrian Emil Chambe-Eng (macpon7)
on 2014-04-01 10:41
Hi all!
I have a few questions for the better population of Ruby programmers out
there:

1. Is there a way to pull a random variable from a list? Like say,
picking a random name from a list of 10 names.

2. This one is sort of linked to the first one. Is there a way to
generate a random whole number from within a percentage range? Like
this: money┬▒27%, where money is a variable.

I'm not sure if this is the right forum, but looking forward to
responses anyways.
249c7fd851c5c5ac5a1abdb756472ae1?d=identicon&s=25 Arup Rakshit (my-ruby)
on 2014-04-01 15:03
Adrian Emil Chambe-Eng wrote in post #1141645:
> Hi all!
> I have a few questions for the better population of Ruby programmers out
> there:
>
> 1. Is there a way to pull a random variable from a list? Like say,
> picking a random name from a list of 10 names.

I understand this question. So here is my answer :

irb(main):001:0> %w( foo bar baz bbc app fiz biz)
=> ["foo", "bar", "baz", "bbc", "app", "fiz", "biz"]
irb(main):002:0> ar = %w( foo bar baz bbc app fiz biz)
=> ["foo", "bar", "baz", "bbc", "app", "fiz", "biz"]
irb(main):004:0> ar.sample
=> "bbc"
irb(main):005:0> ar.sample
=> "foo"
irb(main):006:0>

Look - http://www.ruby-doc.org/core-2.1.1/Array.html#meth...
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2014-04-06 21:34
Adrian Emil Chambe-Eng wrote in post #1141645:
> Is there a way to
> generate a random whole number from within a percentage range? Like
> this: money┬▒27%, where money is a variable.

irb(main):001:0> money = 5.7
=> 5.7
irb(main):002:0> money + money * 0.27
=> 7.239000000000001
irb(main):003:0> money - money * 0.27
=> 4.161
irb(main):004:0> range = (money - money * 0.27)..(money + money * 0.27)
=> 4.161..7.239000000000001
irb(main):005:0> rand range
=> 5.525146865124329
irb(main):006:0> rand range
=> 5.474952173837266
irb(main):007:0> rand range
=> 5.416611433225164
irb(main):008:0> rand range
=> 4.237756781771725
irb(main):009:0> rand range
=> 6.395378295680288
irb(main):010:0> rand range
=> 6.720311855290826
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.