Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions spec/ruby/core/struct/dig_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
@instance.dig(:a, :a).should == { b: [1, 2, 3] }
end

it "returns the value by the index" do
instance = Struct.new(:a, :b).new(:one, :two)
instance.dig(0).should == :one
instance.dig(1).should == :two
end

it "returns the nested value specified if the sequence includes an index" do
@instance.dig(:a, :a, :b, 0).should == 1
end
Expand Down
21 changes: 15 additions & 6 deletions src/main/ruby/truffleruby/core/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -252,13 +252,22 @@ def initialize_copy(other)
_attrs[var]
end

def dig(key, *more)
result = nil
begin
result = self[key]
rescue IndexError, NameError
nil # nothing found with key
private def read_or_nil(var)
case var
when Symbol, String
return unless _attrs.include?(var.to_sym)
else
var = Integer(var)
a_len = _attrs.length
return if (var > a_len - 1) || (var < -a_len)
var = _attrs[var]
end

Primitive.object_hidden_var_get(self, var)
end

def dig(key, *more)
result = read_or_nil(key)
if Primitive.nil?(result) || more.empty?
result
else
Expand Down
6 changes: 1 addition & 5 deletions src/main/ruby/truffleruby/core/truffle/diggable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ def self.dig(obj, idxs)
when Array
obj = obj.at(idx)
when Struct
begin
obj = obj[idx]
rescue IndexError, NameError
obj = nil
end
obj = obj.__send__(:read_or_nil, idx)
end

return nil if Primitive.nil?(obj)
Expand Down