Reputation: 10378
I go throw this guide-ruby-collections-iv-tips-tricks article
Array.new(3, rand(100))
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]
That' ok
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.
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: What is meaning of *several_variants
here.
2: Where if the actual definition of this method.
Suppose I've a class Test; end
How might I could write #new
method which can accept array, optional-hash and block
?
Upvotes: 2
Views: 334
Reputation: 15559
1: what is meaning of *several_variants here.
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 the actual definition of this method.
It's in C: https://github.com/ruby/ruby/blob/trunk/array.c#L5746 and https://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:
how might i write #new method which can accept array, optional hash and block ?
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
will have all the arguments, and &blk
will have a block, if you were passed one.
Upvotes: 3