方法和变量名称是相同的

nev*_*ame 10 ruby

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

hello = "hello from variable"

def hello
  "hello from method"
end

puts hello
Run Code Online (Sandbox Code Playgroud)

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

Jör*_*tag 19

局部变量和方法之间的模糊性仅出现在没有参数列表的无接收器消息发送中.因此,解决方案显而易见:要么提供接收器,要么提供参数列表:

self.hello
hello()
Run Code Online (Sandbox Code Playgroud)

也可以看看

  • 完美答案. (2认同)

Nak*_*lon 14

试试这个:

puts hello()
Run Code Online (Sandbox Code Playgroud)

  • 因为您明确地调用了一个方法.你知道,最好只使用不同的名字...... (2认同)

And*_*imm 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
Run Code Online (Sandbox Code Playgroud)