Reputation: 203
Hey guys I am new to Ruby. I have a question: Do methods have to be always inside classes?
Upvotes: 2
Views: 168
Reputation: 369458
Hey guys I am new to Ruby. I have a question: Do methods have to be always inside classes?
No.
Methods have to be always inside modules. (Class are modules, too.)
Example:
module Foo
def bar; end
end
There is no class here.
Upvotes: 2
Reputation: 36101
Technically they are aways defined inside a class, but this doesn't mean you always need to open a class to define a method.
Here is what might look like a top-level function in other languages:
def foo
puts self
puts self.class
end
If we simply call foo
, we'll get:
main
Object
This actually defined a private instance method in the Object
class. We see that self
in the top-level scope is a special object called main
.
On the other hand, we can try to call this method on other stuff:
'bar'.foo #!> private method `foo' called for "bar":String (NoMethodError)
This errorred out as foo
is private. We can use a special method called send
to invoke private methods:
'bar'.send :foo
Gets us:
bar
String
We can also define methods in the so-called singleton classes. You can think of them as classes with only a single instance. For example:
foo = 'foo'
def foo.bar
puts 'baz'
end
foo.bar # => baz
'quix'.bar # !> undefined method `bar' for "quix":String
'foo'.bar # !> undefined method `bar' for "foo":String
puts (foo.singleton_class.instance_methods - Object.instance_methods).first
# => bar
Here the bar
method was defined on the singleton class of foo
. Note that even another string with the same contents is still a difference instance, hence it doesn't have the bar
method.
Upvotes: 2