8

Possible Duplicate:
Ruby functions vs methods

Im just reading some ruby documentation and t seems to use the term function and method in an interchangeable way, i jut wanted to know if there is any distinction?

the docs im looking at refer to this as a function:

def saysomething()
  puts "Hello"
end

saysomething

and this a method:

def multiply(val1, val2 )
  result = val1 * val2
  puts result
end

this may be a something semantic but i wanted to check

jt

Community
  • 1
  • 1
jonathan topf
  • 7,897
  • 17
  • 55
  • 85

1 Answers1

17

In Ruby, there are not two separate concepts of methods and functions. Some people still use both terms, but in my opinion, using "function" when talking about Ruby is incorrect. There do not exist executable pieces of code that are not defined on objects, because there is nothing in Ruby that is not an object.

As Dan pointed out, there's a way to call methods that makes them look like functions, but the underlying thing is still a method. You can actually see this for yourself in IRB with the method method.

> def zomg; puts "hi"; end
#=> nil
> method(:zomg)
#=> #<Method: Object#zomg>
> Object.private_instance_methods.sort
#=> [..., :zomg]
# the rest of the list omitted for brevity

So you can see, the method zomg is an instance method on Object, and is included in Object's list of private instance methods.

Emily
  • 17,813
  • 3
  • 43
  • 47