ruby 内置方法的定义 [英] definition of ruby inbuilt methods

查看:34
本文介绍了ruby 内置方法的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我去扔这个guide-ruby-collections-iv-tips-技巧文章

Array.new(3, rand(100))

这不是完全随机的.看起来 rand(100) 只被评估一次.幸运的是,Array#new 可以接受一个块,它会为每个元素运行该块,并将结果分配给该元素.

That wasn’t exactly random. It looks like rand(100) is only being evaluated once. Fortunately, Array#new can take a block, and it will run the block for each element, assigning the element the result.

Array.new(3) { rand(100) }
=> [10,53,27]

没关系

但是在我可以看到 Array class#new 方法的实际实现的地方,我检查了 Array 的新方法 但还是没有抓住重点.

But where I could see the actual implementation of #new method of Array class, I checked with Array's New Method But Still not getting the point.

因为我正在使用 Rubymine 我也在那里检查过,这是我在那里找到的

As I'm using Rubymine I checked with there also ,this is I found there

def self.new(*several_variants)
    #This is a stub, used for indexing
end

1:这里的*several_variants是什么意思.

2:如果这个方法的实际定义在哪里.

2: Where if the actual definition of this method.

假设我有一个 类测试;结束

我怎样才能编写可以接受 array、optional-hash 和 block#new 方法?

How might I could write #new method which can accept array, optional-hash and block ?

推荐答案

1:这里的 *several_variants 是什么意思.

1: what is meaning of *several_variants here.

这是一个'splat.':

It's a 'splat.':

$ irb
irb(main):001:0> def foo(*bar)
irb(main):002:1> puts bar
irb(main):003:1> puts bar.class
irb(main):004:1> end
=> :foo
irb(main):005:0> foo([1, 2, 3])
1
2
3
Array
=> nil
irb(main):006:0> foo("hello")
hello
Array
=> nil
irb(main):007:0> foo("Hello", "world")
Hello
world
Array
=> nil
irb(main):008:0> foo(a: "hash")
{:a=>"hash"}
Array
=> nil

2: where if 这个方法的实际定义.

2: where if the actual definition of this method.

它在 C 中:https://github.com/ruby/ruby/blob/trunk/array.c#L5746https://github.com/ruby/ruby/blob/trunk/array.c#L722-L777

rb_ary_initialize(int argc, VALUE *argv, VALUE ary)

当然,这没有多大帮助,因为:

Of course, that's not as helpful, since:

我如何编写可以接受数组、可选散列和块的#new 方法?

how might i write #new method which can accept array, optional hash and block ?

通常,在 Ruby 中,您不会编写 new,而是编写 initialize.new 调用 initialize.这样做很简单:

Usually, in Ruby, you don't write a new, you write an initialize. new calls initialize. Doing this is as easy as:

class Foo
  def initialize(*args, &blk)
    # stuff goes here
  end
end

args 将包含所有参数,并且 &blk 将包含一个块,如果您通过了一个.

args will have all the arguments, and &blk will have a block, if you were passed one.

这篇关于ruby 内置方法的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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