ruby内置方法的定义
我去扔这个指南-ruby-collections-iv-tips-tricks文章
Array.new(3, rand(100))
那不完全是随机的。 看起来rand(100)
只被评估一次。 幸运的是, Array#new
可以占用一个块,它将为每个元素运行块,为元素分配结果。
Array.new(3) { rand(100) } => [10,53,27]
那好吧
但是在那里我可以看到Array class
的#new
方法的实际实现,我检查了Array的新方法但是仍然没有得到重点。
因为我正在使用Rubymine
我也在那里检查过, 这是我在那里找到的
def self.new(*several_variants) #This is a stub, used for indexing end
1:这里有*several_variants
是什么意思。
2:凡是这种方法的实际定义。
假设我有一class Test; end
class Test; end
我怎么能写#new
方法,它可以接受array, optional-hash and block
?
1:这里有几个变量的含义是什么。
这是一个’啪啪声’。:
$ 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:如果这个方法的实际定义在哪里。
它位于C: https : //github.com/ruby/ruby/blob/trunk/array.c#L5746和https://github.com/ruby/ruby/blob/trunk/array.c#L722-L777
rb_ary_initialize(int argc, VALUE *argv, VALUE ary)
当然,这不是有用的,因为:
我怎么写#new方法可以接受数组,可选的哈希和块?
通常,在Ruby中,你不写new
,你写一个initialize
。 new
呼叫initialize
。 这样做很简单:
class Foo def initialize(*args, &blk) # stuff goes here end end
args
将拥有所有参数,并且&blk
将有一个块,如果你被传递了一个。