0

I am new to Ruby, and to object oriented programming more generally.

I think what I want is exactly a Ruby translation of this. That is, I want to be able to initialize an instance of the class, and then as soon as a certain attribute is set call a method on it to convert it.

For example, say I had a Weather class with a temperature attribute that I would like converted from Fahrenheit to Celsius as soon as it is set. Here is the way I would like this to behave.

today = Weather.new
today.temp = 32
today.temp     # => 0

How do I do that?

1 Answer 1

1

You can write your own attr_writer-style method to accomplish this. Feel free to comment if this is unclear.

class Weather
  attr_reader :temp
  def temp=(val)
    @temp = f_to_c(val)
  end
  def f_to_c(temp)
    (temp - 32).to_f * (5.0 / 9.0) 
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

I just translated it to my actual context and it works great, thanks. In terms of clarity, I think I don't quite understand what attr_writer is and does, and I need to wrestle with that some. This will help, I think. It definitely helps to see the correct implementation of what I was trying to accomplish.
Module#attr_writer is a method which generates an attribute writer method. Its implementation looks (roughly) like this: class Module; def attr_writer(*methods) methods.each do |method| define_method(:"#{method}=") do |val| instance_variable_set(:"@#{method}", val) end end end end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.