nbwalsh nbwalsh - 4 years ago 93
Ruby Question

Multiple Independent Variable Cases in Ruby

So, I'm new to programming in general, but I'm working on a random roller where 5 variables need to be rolled for a set and then a string printed depending on each variable, but with the exact same conditions but are all independent of each other. The output would then print a list of those strings.

Instead of writing:

n1 = rand(a..f)+a
n2 = rand(a..f)+a
...
n5 = rand(a..f)+a

case n1
when a..c
puts x
when d..f
puts y
else
puts z
end

case n2
when a..c
puts x
when d..f
puts y
else
puts z
end

...

case n5
when a..c
puts x
when d..f
puts y
else
puts z
end


is there a way to write the case as multiple independent variables in an array or something similar so I'd only need to write the conditions once? There could be up to 4 of these sets if the user is unlucky enough to roll that many, and I don't want to have to write the same conditions up to 20 times, as in my particular situation, there are actually 29 conditions for each case.

Thanks for any help!

Answer Source

It sounds like you just need to encapsulate the logic you have in a method that you can apply multiple times. You have a simplified example, but I'll provide a slightly more robust example here to get you on the right path of thinking:

class RollValue
  def initialize(value)
    @value = value
  end

  def message
    case @value
    when a..c
      puts 'x'
    when d..f
      puts 'y'
    else
      puts 'z'
    end
  end
end

RollValue.new('b').message #=> 'x'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download