Sophie Proud Sophie Proud - 1 month ago 7
Ruby Question

Ruby Method Arguments - Can they change truth value automatically?

I have this method

def forest(sword, armour, ring)

with its arguments having
values, which I declare in the main program as

forest false, false, false

If during the program
sword=true && armour=true
, is there any way for Ruby to automatically assess whether the arguments are true or false?
Could I write something like

forest sword-truth-value, armour-truth-value, ring-truth-value?

The program I'm writing is very long and it would take too many code lines to take every single case into consideration.

Thanks for the help!


To achieve what you are looking for, you should wrap the forest method in a class and define each argument as an instance variable.

class Forest

  attr_accessor :sword, :armour, :ring

  def initialize(sword = false, armour = false, ring = false)
    @sword = sword
    @armour = armour
    @ring = ring


So now, you can declare an instance of Forest,

forest =

All the variables default to false, unless you explicitly write true.

With the attr_accessor, you can access and set all the variables.

forest.sword #=> false
forest.sword = true
forest.sword #=> true