Class: JSONP3::SliceSelector
- Defined in:
- lib/json_p3/selector.rb
Overview
The slice selector selects a range of elements from an array.
Instance Attribute Summary collapse
-
#start ⇒ Object
readonly
Returns the value of attribute start.
-
#step ⇒ Object
readonly
Returns the value of attribute step.
-
#stop ⇒ Object
readonly
Returns the value of attribute stop.
Attributes inherited from Selector
Instance Method Summary collapse
- #==(other) ⇒ Object (also: #eql?)
- #hash ⇒ Object
-
#initialize(env, token, start, stop, step) ⇒ SliceSelector
constructor
A new instance of SliceSelector.
- #resolve(node) ⇒ Object
- #to_s ⇒ Object
Methods inherited from Selector
Constructor Details
#initialize(env, token, start, stop, step) ⇒ SliceSelector
Returns a new instance of SliceSelector.
192 193 194 195 196 197 |
# File 'lib/json_p3/selector.rb', line 192 def initialize(env, token, start, stop, step) super(env, token) @start = start @stop = stop @step = step || 1 end |
Instance Attribute Details
#start ⇒ Object (readonly)
Returns the value of attribute start.
190 191 192 |
# File 'lib/json_p3/selector.rb', line 190 def start @start end |
#step ⇒ Object (readonly)
Returns the value of attribute step.
190 191 192 |
# File 'lib/json_p3/selector.rb', line 190 def step @step end |
#stop ⇒ Object (readonly)
Returns the value of attribute stop.
190 191 192 |
# File 'lib/json_p3/selector.rb', line 190 def stop @stop end |
Instance Method Details
#==(other) ⇒ Object Also known as: eql?
231 232 233 234 235 236 237 |
# File 'lib/json_p3/selector.rb', line 231 def ==(other) self.class == other.class && @start == other.start && @stop == other.stop && @step == other.step && @token == other.token end |
#hash ⇒ Object
241 242 243 |
# File 'lib/json_p3/selector.rb', line 241 def hash [@start, @stop, @step, @token].hash end |
#resolve(node) ⇒ Object
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/json_p3/selector.rb', line 199 def resolve(node) return [] unless node.value.is_a?(Array) length = node.value.length return [] if length.zero? || @step.zero? normalized_start = if @start.nil? @step.negative? ? length - 1 : 0 elsif @start&.negative? [length + (@start || raise), 0].max else [@start || raise, length - 1].min end normalized_stop = if @stop.nil? @step.negative? ? -1 : length elsif @stop&.negative? [length + (@stop || raise), -1].max else [@stop || raise, length].min end (normalized_start...normalized_stop).step(@step).map { |i| node.new_child(node.value[i], i) } end |
#to_s ⇒ Object
224 225 226 227 228 229 |
# File 'lib/json_p3/selector.rb', line 224 def to_s start = @start || "" stop = @stop || "" step = @step || 1 "#{start}:#{stop}:#{step}" end |