Martin
Martin

Reputation: 11336

Managing setters and getters methods on ruby

I'm learning about using methods on Ruby the right way. I'm interested in know if this is a common (and suggested) approach to handling setting and getters.

For instance, I have a method that sets a value depending on input and I would like to call the result in different parts of the sites by simply calling getMyMethod as follow without needing to call the setter again.

def setMyMethod(value)
  if value > 10
    result = 'is over 10!'
  else
    result = 'is below 10'
  end
  @methodValue = result
  return @methodValue
end

get getMyMethod
  return @methodValue
end

Is this the right approach to setting and retrieving values from methods?

Upvotes: 1

Views: 126

Answers (1)

Ismael
Ismael

Reputation: 16720

The ruby way would be

def instance_var=(value)
  if value > 10
    result = 'is over 10!'
  else
    result = 'is below 10'
  end
  @instance_var = result # no need for return. In ruby the evaluated value of last line is always returned
end

def instance_var
  @instance_var
end

Maybe you should read something like this http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/

Also you could avoid that 5 lines if statement and one variable easily.

def instance_var=(value)
  @instance_var = value > 10 ? 'is over 10!' : 'is below 10'
end

def instance_var
  @instance_var
end

Upvotes: 4

Related Questions