user6332345
user6332345

Reputation:

How can I call methods from a class in Ruby?

How can I print this method from the class?

I'm new to Ruby so I'm not sure who to print this. I essentially need to enter a number into this method and print.

Similar to a JS function, I know I must use puts, but that's pretty much about it.

class Celcius
  def initialize(temperature)
    @temperature = temperature
  end

  def fahrenheit
    (@temperature * 1.8 + 32).round
  end

  def to_s
    "#{@temperature} degrees C"
  end
end 

Upvotes: 0

Views: 28

Answers (1)

tadman
tadman

Reputation: 211540

Whenever you need to print something:

temp = Celcius.new(120)

puts temp.to_s

Now puts likes to convert things to string, and to_s is the default way of doing this, so this should work:

puts temp

Upvotes: 4

Related Questions