开发者

Method and variable name is the same

开发者 https://www.devze.com 2023-01-16 12:22 出处:网络
If both a method and a variable has the 开发者_如何学Csame name it will use the variable. hello = \"hello from variable\"

If both a method and a variable has the 开发者_如何学Csame name it will use the variable.

hello = "hello from variable"

def hello
  "hello from method"
end

puts hello

Is it possible somehow to use the method instead without changing name?


The ambiguity between local variables and methods only arises for receiverless message sends with no argument list. So, the solution is obvious: either provide a receiver or an argument list:

self.hello
hello()

See also

  • How does ruby allow a method and a Class with the same name?
  • Optional parens in Ruby for method with uppercase start letter?


Try this:

puts hello()


This is more of a comment than an answer, but distinguishing between local variables and methods is vital if you're using an assignment method.

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


puts self.hello

By the way, I agree with Henrik P. Hessel. This is a very horrible piece of code.

0

精彩评论

暂无评论...
验证码 换一张
取 消