Tobias
Tobias

Reputation: 6507

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?

Upvotes: 3

Views: 2077

Answers (4)

Daniel Garmoshka
Daniel Garmoshka

Reputation: 6352

Create alias for global method:

alias hello_global hello

Upvotes: 0

crazycrv
crazycrv

Reputation: 2445

Object.send(:hello,self) also works.

Upvotes: 1

Aleksander Pohl
Aleksander Pohl

Reputation: 1695

This should work

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

Upvotes: 6

Johannes Fahrenkrug
Johannes Fahrenkrug

Reputation: 44808

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.

Upvotes: 3

Related Questions