2010-09-18 148 views
9

如果方法和变量都具有相同的名称,它将使用该变量。方法和变量名称相同

hello = "hello from variable" 

def hello 
    "hello from method" 
end 

puts hello 

是否有可能以某种方式使用该方法而不更改名称?

+3

为什么要这样做? – 2010-09-18 11:50:06

+9

@Henrik:我想更好地了解ruby – 2010-09-18 12:08:46

+2

松本幸弘(Ruby的创造者)在一本名为“Ruby In A Null Shell”的书中提到了这件事(在许多其他伟大的事情中)。由O'Reilly出版)。这本书非常适合回答你提出的问题的深度。 – Zabba 2010-09-19 05:43:15

回答

12

试试这个:

puts hello() 
+0

没错,但请详细说明为什么使用圆括号表示这项工作 – Zabba 2010-09-19 05:46:52

+2

因为您明确调用方法。更好的是,你知道,首先使用不同的名字... – 2010-09-20 00:26:35

1
puts self.hello 

顺便说一句,我同意与Henrik P. Hessel的。 这是一段非常可怕的代码。

5

这是一个多一条评论答案,但区分局部变量和方法对于使用赋值方法至关重要。

class TrafficLight 
    attr_accessor :color 

    def progress_color 
    case color 
    when :orange 
     #Don't do this! 
     color = :red 
    when :green 
     #Do this instead! 
     self.color = :orange 
    else 
     raise NotImplementedError, "What should be done if color is already :red? Check with the domain expert, and build a unit test" 
    end 
    end 
end 

traffic_light = TrafficLight.new 
traffic_light.color = :green 
traffic_light.progress_color 
traffic_light.color # Now orange 
traffic_light.progress_color 
traffic_light.color # Still orange 
+1

谢谢你,这正是给我的麻烦。 – 2013-12-11 16:42:11

相关问题