在ruby中,方法和函数之间有区别 [英] in ruby is there a distinction between a method and function

查看:40
本文介绍了在ruby中,方法和函数之间有区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Ruby函数与方法

我只是在阅读一些ruby文档,并且似乎以一种可互换的方式使用术语函数和方法,我想知道是否存在任何区别?

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

这是一种方法:

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

这可能是一种语义,但我想检查

this may be a something semantic but i wanted to check

jt

推荐答案

在Ruby中,方法和函数没有两个独立的概念.有些人仍然使用这两个术语,但我认为在谈论Ruby时使用函数"是不正确的.没有存在未在对象上定义的可执行代码段,因为Ruby中没有任何对象不是对象.

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.

正如Dan所指出的那样,有一种方法可以使方法像函数一样调用它们,但其底层内容仍然是方法.实际上,您可以使用 method 方法在IRB中亲自看到这一点.

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

因此您可以看到,方法 zomg 是Object的实例方法,并包含在Object的私有实例方法列表中.

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

这篇关于在ruby中,方法和函数之间有区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆