简体   繁体   中英

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM