Novice programmer asking for help :P

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.

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#method-i-sample

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs