Why are global methods allowed to define outside a class in Ruby?

I read this:

Let's start with a simple Ruby program. Well write a method that returns a welcome, personalized greeting.

def say_goodnight(name)
    result = "Goodnight, " + name
    return result
end

I understand that a method is a function or routine that is defined in a class that can be associated with a class (class method) or with an object (instance method).

Then, how could this be a method if it was not defined inside the class?

+4
source share
1 answer

Ruby , private Object, , Ruby. Ruby - , , .

def say_goodnight(name)
    result = "Goodnight, " + name
    return result
end

Object.private_methods.include? :say_goodnight
=> true

private Object, , . , ?

, Ruby Object, main, , . , , main ( Object), .

# In irb:
self
=> main
self.class
=> Object
self.private_methods.include? :say_goodnight
=> true

: , , main .

+9

Source: https://habr.com/ru/post/1569895/


All Articles