Ruby实例方法和变量 [英] Ruby Instance Methods and Variables

查看:117
本文介绍了Ruby实例方法和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些东西我不明白ruby 类的实例变量或方法**
所以我有这个代码,继续给我这个错误,我不能理解

There is something that i don't understand about ruby class instance variable or methods**. So i have this code that keeps on giving me this error and i cant understand

看起来ruby认为我试图调用Float.in_celsius,但我想要在我的类实例中进行此调用。

Looks ruby thinks that i am trying to call for Float.in_celsius but I want to make this call within my class instance.

#-----------------------------------
def ftoc(fr)
fr = fr.to_f
if (fr == 32)
    c = 0
elsif (fr == 212)
    c = 100
else 
    c = (fr-32.0)*(5.0/9.0)
end

return c
end

def ctof (cl)
cl = cl.to_f
f = (cl*(9.0/5.0))+32.0
return f
end
#-----------------------------------

class Temperature
attr_accessor :in_celsius, :in_fahrenheit 

#class metods 
def self.from_celsius(cel)
    puts "from celsious\n"
    puts "cel: #{cel}\n"
    @in_fahrenheit = cel
    @in_celsius = ctof(cel)
    puts "==============================\n"
    return @in_celsius
end

def self.in_celsius
    @in_celsius
end


end


puts "==============================\n"
puts Temperature.from_celsius(50).in_celsius
puts Temperature.from_celsius(50).in_fahrenheit

且错误是
test.rb:54 :in'< main>':122.0的未定义方法in_celsius:float(noMethod Error)
在这里输入代码

推荐答案

你对Ruby如何工作有一个根本性的误解。现在,所有的变量和方法都定义在类级别。这意味着你在方法中做的所有事情都直接作用于类本身。而应创建温度实例

You have a fundamental misunderstanding of how classes work in Ruby. Right now all of your variables and methods are defined at class level. That means that everything you do in the methods is acting directly on the class itself. Instead, you should create instances of Temperature.

class Temperature
  # special method called when creating a new instance
  def initialize celsius
    @in_celsius = celsius
    @in_fahrenheit = celsius * 9 / 5.0 + 32
  end

  def self.from_celsius celsius
    new celsius # built in method to create an instance, passes argument to initialize
  end

  # we defined initialize using celsius, so here we must convert
  def self.from_fahrenheit fahrenheit
    new((fahrenheit - 32) * 5 / 9.0)
  end

  private_class_method :new # people must use from_celsius or from_fahrenheit

  # make instance variables readable outside the class
  attr_accessor :in_celsius, :in_fahrenheit
end

Temperature.from_celsius(50).in_celsius

此代码不完美( from_fahrenheit 做一个冗余转换),但它应该给你如何重新设计你的类的想法。

This code isn't perfect (from_fahrenheit does a redundant conversion) but it should give you the idea of how to redesign your class.

这篇关于Ruby实例方法和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆