2013-10-23 176 views
1

所以我写了一个简单的产品类,并从类中实例化。红宝石方法定义

#This class defines a product 
#It provides a method that can be used to provide a discount on any given instance of a product 

class Product 
    attr_reader :name, :description, :price 

    def initialize (name, description, price) 
    @name = name 
    @description = description 
    @price = Float(price) 
    end 

    def price=(sale_price) 
    @price = sale_price 
    end 

    def to_s 
    "Name: #{@name}, Description: #{@description}, Price: #{@price}." 
    end 
end 

my_product = Product.new("redshoes","These are beautiful",50.00) 
my_product.price = my_product.price * 0.50 
puts "The new sale price of #{my_product.name} is #{my_product.price}" 

我有一个问题我需要澄清那就是当我这样定义一个方法:

def price=(sale_price) 
    @price = sale_price 
end 

我定义的方法,并在同一时间将其分配给一个变量。第一行“def price =(sale_price)”有点令人困惑,因为我基于在线研究和书籍撰写了这篇文章,但如果我可以对此进行一些澄清,这将会有所帮助。

+0

谢谢你们。@@ Guilherme Bernal由于您提到两种方法相同,所以我对代码进行了更改,但是我得到的错误数量参数错误(1代表0)(ArgumentError) def price(sale_price) @price = sale_price end def to_s “名称:#{@ name},描述:#{@ description},价格:#{@ price}。” 结束 结束 my_product = Product.new( “redshoes”, “这是美丽的”,50.00) my_product.price = my_product.price * 0.50 看跌期权“的#新的销售价格{} my_product.name是# {my_product.price}“ – user2912496

回答

0

这是如何红宝石做setter方法。请记住,不要求方法名称和变量名称匹配,也不要求实际进行任何分配,尽管这在大多数情况下可能是很好的做法。

,但你可以有:

def confuse=(ignore_me) 
    puts "Silly human, #{ignore_me} is being ignored!" 
end 

这将被调用任何时候你有

object.confuse = something 

和不执行任何实际的分配。

1

这只是方法的名称。

def set_price(p) 
    @price = p 
end 

或:

def price=(p) 
    @price = p 
end 

你调用这个方法:

product.set_price(100) 
product.price=(100) 

看到了吗?不用找了。魔术时显示红宝石让你省略括号和平等和名称的其余部分之间加空格:

product.price = 100 

这仅仅是一个常用的方法调用。没有什么奇特的事情发生。

+2

Nit-pick:这个解释并不完全准确。 Ruby不仅允许你省略parens并在setter方法名称的等号周围添加空格 - setter语法是一个特殊的构造,它调用底层的setter方法,但不同于直接调用它。例如,假设我们的setter是'def price =(p)@price = p; 42结束'。如果写'product.price = 100''等于'product.send(:price =,100)',我们预计这两个调用返回42,而'product.price = 100'返回100而'product'。发送(:price =,100)'返回42。 – Chuck

1

我认为如果你明白def实际上在做什么,它会更有意义。在def price=(sale_price)的示例中,“price =”是您在Product类中定义的方法的名称。当您拨打my_product.price =时,您正在调用您定义的方法“price =”。

除非将实例变量@price设置为等于方法的输入(变量sale_price),否则实际上并没有更改任何值。

原因my_product.price(不带等号)的工作原理是,因为你已经定义的属性使用attr_reader :price,这是给你的读访问实例变量@price一个有用的方式称为:price

希望有所帮助。