Class: Remap::Selector::Index

Inherits:
Unit
  • Object
show all
Defined in:
lib/remap/selector/index.rb

Overview

Selects value at given index

Examples:

Select the value at index 1 from a array

state = Remap::State.call([:one, :two, :tree])
index = Remap::Selector::Index.new(1)

result = index.call(state) do |element|
  value = element.fetch(:value)
  element.merge(value: value.upcase)
end

result.fetch(:value) # => :TWO

Instance Method Summary collapse

Instance Method Details

#call(state) {|| ... } ⇒ State<U>

Selects the #indexth element from state and passes it to block

Parameters:

  • state (State<Array<T>>)

Yield Parameters:

Yield Returns:

Returns:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/remap/selector/index.rb', line 31

def call(state, &block)
  unless block
    raise ArgumentError, "The index selector requires an iteration block"
  end

  array = state.fetch(:value) { return state }

  unless array.is_a?(Array)
    state.fatal!("Expected an array got %s", array.class)
  end

  value = array.fetch(index) do
    state.ignore!("Index [%s] (%s) not found", index, index.class)
  end

  state.set(value, index: index).then(&block)
end

#indexInteger

Returns:

  • (Integer)


21
# File 'lib/remap/selector/index.rb', line 21

attribute :index, Integer