Last active
December 21, 2015 22:58
-
-
Save jackjennings/962e3741e50cec11bdba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Possible passing
dig
implementation?