Skip to content

Instantly share code, notes, and snippets.

@jackjennings
Last active December 21, 2015 22:58
Show Gist options
  • Save jackjennings/962e3741e50cec11bdba to your computer and use it in GitHub Desktop.
Save jackjennings/962e3741e50cec11bdba to your computer and use it in GitHub Desktop.
$ cutest dig.rb
.
test: should get remaining segments from ReturnsSegmentsDigger
line: assert_equal ['two', 0], data.dig('one', 'two', 0)
file: dig.rb +53
Cutest::AssertionFailed: ["two", 0] != [0]
module Diggable
def dig(*segments)
object = self
while segments.any?
current_segment, *segments = segments
if object.respond_to?(:dig)
return object.dig(*segments)
elsif object.respond_to?(:[])
object = object[current_segment]
else
return nil
end
end
object
end
refine Hash do
include Diggable
end
refine Array do
include Diggable
end
refine Struct do
include Diggable
end
end
using Diggable
class ReturnsSegmentsDigger
include Diggable
def dig(*segments)
segments
end
end
test "should get nested data" do
data = {"one" => {"two" => [3] }}
assert_equal 3, data.dig('one', 'two', 0)
end
test "should get remaining segments from ReturnsSegmentsDigger" do
data = {"one" => ReturnsSegmentsDigger.new}
assert_equal ['two', 0], data.dig('one', 'two', 0)
end
@jackjennings
Copy link
Author

Possible passing dig implementation?

  def dig(*segments)
    object = self

    while segments.any?
      if object.respond_to?(:dig)
        return object.dig(*segments)
      elsif object.respond_to?(:[])
        current_segment, *segments = segments
        object = object[current_segment]
      else
        return nil
      end
    end

    object
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment