简体   繁体   中英

How to call a method from the global scope with same name as an instance method in ruby?

Suppose I have the global method hello(name) and an instance method hello like this:

def hello(name)
  puts("Hello " + name)
end

class String
  def hello
    hello(self)         # does not work, see below
  end
end

I want to be able to say

"world".hello()

but ruby won't let me. It complains

in `hello': wrong number of arguments (1 for 0) (ArgumentError)

What am I missing?

This should work

class String
  def hello
    Kernel.send(:hello,self)
  end
end

This question answers this exact question: How to access a (shadowed) global function in ruby

Basically, def on the global object creates a private method on Object , so you have to jump through some hoops to call it.

Object.send(:hello,self)也有效。

为全局方法创建别名:

alias hello_global hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM