Ruby:作为数组元素的方法 - 它们如何工作? [英] Ruby: methods as array elements - how do they work?

查看:31
本文介绍了Ruby:作为数组元素的方法 - 它们如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能不是你应该在家里尝试的东西,但出于某种原因,我尝试在 Ruby 中创建一个方法数组.

This probably isn't something you should try at home, but for some reason or another I tried to create an array of methods in Ruby.

我首先定义了两个方法.

I started by defining two methods.

irb(main):001:0> def test1
irb(main):002:1>   puts "test!"
irb(main):003:1> end
=> nil
irb(main):004:0> def test2
irb(main):005:1>   puts "test2!"
irb(main):006:1> end
=> nil

当您尝试将其放入实际数组时,会发生奇怪的事情.似乎同时运行这两种方法.

The weird thing happens when you try to put it into an actual array. It seems to run both methods.

irb(main):007:0> array = [test1, test2]
test!
test2!
=> [nil, nil]

之后,数组为空.

irb(main):008:0> puts array


=> nil

有人可以向我解释为什么它运行这些方法吗?除此之外,整个练习都非常需要驱魔师?

Can someone explain to me why it runs the methods? Other than that the whole excercise is seriously in need of an exorcist?

推荐答案

您在数组中存储的是调用方法的结果,而不是方法本身.

What you're storing in your array is the result of calling your methods, not the methods themselves.

def test1
  puts "foo!"
end

def test2
  puts "bar!"
end

您可以像这样存储对实际方法的引用:

You can store references to the actual methods like this:

> arr = [method(:test1), method(:test2)]
# => [#<Method: Object#test1>, #<Method: Object#test2>] 

稍后,您可以像这样调用引用的方法:

Later, you can call the referenced methods like this:

> arr.each {|m| m.call }
foo!
bar!

这篇关于Ruby:作为数组元素的方法 - 它们如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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