Ruby, Source Code of Splat?
Asked Answered
C

2

8

Someone asked about the splat operator yesterday, and I wanted to see the source code... would that be written in C or in Ruby? Where would it be found?

Claustral answered 28/5, 2009 at 15:16 Comment(0)
E
2

The splat operator is poorly documented in the core Ruby documentation as of Ruby 2.4. It's a core feature of the language, though, and the source code for the splat operator can be found in vm_eval.c under rb_yield_splat(VALUE values).

The unit test for rb_yield_splat makes it clearer what is happening:

it "yields with passed array's contents" do
  ret = nil
  @s.rb_yield_splat([1, 2]) { |x, y| ret = x + y }
  ret.should == 3
end
Elephus answered 2/8, 2017 at 1:57 Comment(3)
that's great, but how did you know where the source is?Claustral
I searched for it in the Ruby git repository. Limit the search to C files, then read the source code until you find it.Elephus
Wow that's great. Thank you.Claustral
S
7

Some quick Google searching turned up that it's implemented in eval.c. You can find references to "splat" in a few places in the file, but I'm not familiar enough with the inner workings of Ruby to make any sense of it.

Sherysherye answered 28/5, 2009 at 15:30 Comment(3)
Thanks for that, Martin. Just trying to make sense of the Ruby world. So basically, if it's ruby and not rails, the source is probably not in Ruby, which makes sense.Claustral
The splat operator is part of the core ruby language, not a library feature. It can be used on any object that defines a #to_ary method, but when used to collect multiple values into a single variable (as in a, *b = 1,2,3,4,5) it will always create an Array.Schnapp
@Rampion, thanks for that. So I guess my real question would be: are there any "library features" (for which the source code is in Ruby) which do not need a "require?"Claustral
E
2

The splat operator is poorly documented in the core Ruby documentation as of Ruby 2.4. It's a core feature of the language, though, and the source code for the splat operator can be found in vm_eval.c under rb_yield_splat(VALUE values).

The unit test for rb_yield_splat makes it clearer what is happening:

it "yields with passed array's contents" do
  ret = nil
  @s.rb_yield_splat([1, 2]) { |x, y| ret = x + y }
  ret.should == 3
end
Elephus answered 2/8, 2017 at 1:57 Comment(3)
that's great, but how did you know where the source is?Claustral
I searched for it in the Ruby git repository. Limit the search to C files, then read the source code until you find it.Elephus
Wow that's great. Thank you.Claustral

© 2022 - 2024 — McMap. All rights reserved.