如何处理Ruby中的方法顺序? [英] How to handle Method Order in Ruby?

查看:38
本文介绍了如何处理Ruby中的方法顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ruby 的新手.我熟悉其他几种语言.我的问题是关于无序调用方法.例如:

I am new to Ruby. I am familiar with several other languages. My question is about calling methods out of order. For example:

def myfunction
    myfunction2
end

def myfunction2
    puts "in 2"
end

如何在声明 myfunction2 之前调用它?多种语言允许您在顶部或 .h 文件中声明它.红宝石如何处理它?

How could I call myfunction2 before it is declared? Several languages let you declare it at the top or in a .h file. How does ruby handle it?

我是否总是需要遵循这个:

Do I always need to follow this:

def myfunction2
    puts "in 2"
end

def myfunction
    myfunction2
end

主要是当我需要在 def initialize 中为一个类调用另一个方法时,这会让我感到困扰.

Mainly this bugs me when I need to call another method inside of def initialize for a class.

推荐答案

在定义方法之前不能调用它.但是,这并不意味着您不能在 myfunction2 之前定义 myfunction!Ruby 具有后期绑定,因此在调用 myfunction 之前,myfunction 中对 myfunction2 的调用不会与实际的 myfunction2 相关联代码>.这意味着只要对 myfunction 的第一次调用是在 myfunction2 声明之后完成的,你应该没问题.

You can not call a method before you define it. However, that does not mean you can't define myfunction before myfunction2! Ruby has late binding, so the call to myfunction2 in myfunction will not be associated with the actual myfunction2 before you call myfunction. That means that as long as the first call to myfunction is done after myfunction2 is declared, you should be fine.

所以,这没问题:

def myfunction
    myfunction2
end

def myfunction2
    puts "in 2"
end

myfunction

而这不是:

def myfunction
    myfunction2
end

myfunction

def myfunction2
    puts "in 2"
end

这篇关于如何处理Ruby中的方法顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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