Class: KeyTree::Path
- Inherits:
-
Array
- Object
- Array
- KeyTree::Path
- Defined in:
- lib/key_tree/path.rb
Overview
Representation of the key path to a value in a key tree
Class Method Summary collapse
-
.[](*keys_or_paths) ⇒ Object
KeyTree::Path[
key_or_path
, …].
Instance Method Summary collapse
- #+(other) ⇒ Object
- #<<(other) ⇒ Object
-
#conflict?(other) ⇒ Boolean
Would
other
conflict?. -
#drop(prefix) ⇒ Object
drop(
prefix
). -
#initialize(key_or_path = []) ⇒ Path
constructor
KeyTree::Path.new(
key_or_path
). - #inspect ⇒ Object
-
#prefix?(other) ⇒ Boolean
Is
other
a prefix?. - #to_s ⇒ Object
Constructor Details
#initialize(key_or_path = []) ⇒ Path
KeyTree::Path.new(key_or_path
)
Make a new key path from a dot separated string, single symbol, or array of strings or symbols.
Example:
KeyTree::Path.new("a.b.c")
=> ["a", "b", "c"]
27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/key_tree/path.rb', line 27 def initialize(key_or_path = []) case key_or_path when String initialize(key_or_path.split('.')) when Symbol initialize(key_or_path.to_s) when Array key_or_path.each { |key| append(key.to_sym) } else raise ArgumentError, 'key path must be String, Symbol or Array of those' end end |
Class Method Details
Instance Method Details
#+(other) ⇒ Object
59 60 61 |
# File 'lib/key_tree/path.rb', line 59 def +(other) dup << other end |
#<<(other) ⇒ Object
48 49 50 51 52 53 54 55 56 57 |
# File 'lib/key_tree/path.rb', line 48 def <<(other) case other when Path other.reduce(self) do |result, key| result.append(key) end else self << Path[other] end end |
#conflict?(other) ⇒ Boolean
Would other
conflict?
91 92 93 |
# File 'lib/key_tree/path.rb', line 91 def conflict?(other) prefix?(other) || other.prefix?(self) if self != other end |
#drop(prefix) ⇒ Object
drop(prefix
)
Returns a key path without the leading prefix
drop(n
)
Returns a key path without the first n elements
71 72 73 74 75 76 77 78 79 |
# File 'lib/key_tree/path.rb', line 71 def drop(prefix) case prefix when Path return self unless prefix?(other) drop(other.length) else super(prefix) end end |
#inspect ⇒ Object
44 45 46 |
# File 'lib/key_tree/path.rb', line 44 def inspect %("#{self}") end |
#prefix?(other) ⇒ Boolean
Is other
a prefix?
83 84 85 86 87 |
# File 'lib/key_tree/path.rb', line 83 def prefix?(other) return false if other.length > length key_enum = each other.all? { |other_key| key_enum.next == other_key } end |
#to_s ⇒ Object
40 41 42 |
# File 'lib/key_tree/path.rb', line 40 def to_s join('.') end |