Ahmad Al-kheat
Ahmad Al-kheat

Reputation: 1795

Source code for uniq method in Ruby

In pry I'm typing

Array.instance_method(:uniq).source_location

Expected : source code location for uniq

Actual: nil

What am I doing wrong?

Upvotes: 2

Views: 679

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

Method#source_location returns the location of the Ruby source code. Depending on the Ruby implementation you are using, there may not be Ruby source code. In MRI, YARV, MRuby, or tinyrb, the method may be implemented in C, in XRuby or JRuby, it may be implemented in Java, in Ruby.NET or IronRuby, it may be implemented in C#, in MagLev, it may be implemented in Smalltalk, in MacRuby or RubyMotion, it may be implemented in Objective-C, in Topaz, it may be implemented in RPython, in Cardinal, it may be implemented in Perl6, and in Rubinius, it may be implemented in C++.

However, in Rubinius, many more methods are implemented in Ruby than in other Ruby implementations, so the chance that you will actually get a source_location is much greater. For example, this is what I get on Rubinius:

Array.instance_method(:uniq).source_location
# => ['kernel/common/array.rb', 1640]

This is what kernel/common/array.rb looks like (the code has changed since I compiled my version of Rubinius, that's why the line numbers don't match):

def uniq(&block)
  dup.uniq!(&block) or dup
end

Upvotes: 2

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You might want to re-read the doc on Method#source_location:

Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native)

Array as you might notice in the top-left corner of this doc page, is defined in proc.c, that said it’s methods are native.

Upvotes: 3

Related Questions