如何在Ruby中处理方法顺序?

cod*_*ded 8 ruby

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

def myfunction
    myfunction2
end

def myfunction2
    puts "in 2"
end
Run Code Online (Sandbox Code Playgroud)

我怎么能在声明之前调用myfunction2?有几种语言可以在顶部或.h文件中声明它.红宝石如何处理它?

我是否总是需要遵循:

def myfunction2
    puts "in 2"
end

def myfunction
    myfunction2
end
Run Code Online (Sandbox Code Playgroud)

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

Ida*_*rye 20

在定义方法之前,无法调用方法.但是,这并不意味着你myfunction之前无法定义myfunction2!Ruby有后期绑定,因此调用myfunction2myfunction不会与实际关联myfunction2打电话之前myfunction.这意味着只要第一次调用myfunction myfunction2声明之后完成,你应该没问题.

所以,这没关系:

def myfunction
    myfunction2
end

def myfunction2
    puts "in 2"
end

myfunction
Run Code Online (Sandbox Code Playgroud)

这不是:

def myfunction
    myfunction2
end

myfunction

def myfunction2
    puts "in 2"
end
Run Code Online (Sandbox Code Playgroud)

  • 请注意,通过添加`BEGIN`语句可以将非工作示例敲入工作代码:`BEGIN {def myfunction2; 把"放在2";结束}`. (2认同)
  • @steenslag更好的方法是添加一个`END`语句:`END {myfunction}`. (2认同)

Lee*_*ley 7

方法顺序唯一重要的是纯粹的程序代码,这通常是短视的,给出两种方法:

def greet
  puts "%s, Dave" % random_greeting
end
# If I try to use `greet` here, it'll raise a NoMethodError
def random_greeting
  ["Hello", "Bonjour", "Hallo"].sample
end
# I can use `greet` here, because `random_greeting` is now defiend
Run Code Online (Sandbox Code Playgroud)

这可以正常工作,除非你想greetrandom_greeting定义之前使用,所有非平凡代码解决这个问题的方法是将行为包装在一个类中:

class Doorman
  def greet
    puts "%s, Dave" % random_greeting
  end
  def random_greeting
    ["Hello", "Bonjour", "Hallo"].sample
  end
end
Doorman.new.greet
Run Code Online (Sandbox Code Playgroud)

然后,人们可以Doorman.new.greet通过将行为包装在一个类中来更好地模拟应用程序(例如,酒店代码中的不同对象可以提供不同的问候语),并且还可以保持main名称空间的清晰.

mainRuby中的对象已经定义了114个方法,因此将自己的方法放在表示项目模型中的actor或对象的类中要好得多.

除了你在关于初始化类的问题中所说的,这是完全可能的:

class Doorman
  def initialize
    puts "%s, I'm a new Doorman instance" & random_greeting
  end
  def greet
  "%s, Dave" % random_greeting
  end
  def random_greeting
    ["Hello", "Bonjour", "Hallo"].sample
  end
end
Run Code Online (Sandbox Code Playgroud)

尽管random_greeting在我们编写时没有定义该方法initailize,但是在initialize调用之前定义了整个类.再次,通过包装类,这使生活更容易,更清洁,并意味着事物保持封装.