Class: Array

Inherits:
Object show all
Defined in:
lib/patch/let.rb,
lib/patch/foobar.rb,
lib/patch/lambda.rb

Overview

Monkey patches for use in Lambda

Instance Method Summary collapse

Instance Method Details

#hashy?Boolean

Checks if the array is “hashy”, meaning it consists entirely of two-element arrays. This structure is suitable for conversion to a Hash using to_h.

Examples:

[[:a, 1], [:b, 2]].hashy?  # => true
[["key1", "value1"]].hashy? # => true
[[1, 2, 3], [:b, 2]].hashy? # => false (first item has 3 elements)
[1, 2, 3].hashy?            # => false (items are not arrays)
[[], [:a, 1]].hashy?       # => false (first item is empty)


40
41
42
# File 'lib/patch/let.rb', line 40

def hashy?
  all? { |item| item.is_a?(Array) && item.size == 2 }
end

#op(method) ⇒ Object

Allows for this:

  • ‘[1, 2, 3].op(:+) # => 6`

  • ‘[1, 2, 3].op(:-) # => -4`

Not the same as [reduce] or [inject] The method argument is supposed to be an instance method for the first element of the array.



12
13
14
# File 'lib/patch/lambda.rb', line 12

def op(method)
  first.send(method, slice(1..))
end

#qoq(default = nil) ⇒ Object

Same as [Array#pop] but returns default if the array is empty.



17
18
19
# File 'lib/patch/lambda.rb', line 17

def qoq(default = nil)
  empty? ? default : pop
end

#restArray

Returns the rest of the array (all elements except the first). Returns an empty array if the original array has 0 or 1 element.

Examples:

[1, 2, 3, 4].rest # => [2, 3, 4]
[1].rest          # => []
[].rest           # => []


252
253
254
# File 'lib/patch/foobar.rb', line 252

def rest
  drop 1
end

#simplifyObject, Array

Simplifies the array: if it contains exactly one element, returns that element. Otherwise, returns the array itself.

Examples:

[42].simplify    # => 42
["hello"].simplify # => "hello"
[1, 2].simplify  # => [1, 2]
[].simplify      # => []


265
266
267
# File 'lib/patch/foobar.rb', line 265

def simplify
  size == 1 ? fetch(0) : self
end