Module: Ramaze::CoreExtensions::Array

Defined in:
lib/ramaze/snippets/array/put_within.rb

Overview

Extensions for Array

Instance Method Summary collapse

Instance Method Details

#put_after(element, object) ⇒ Object

a = [1, 2, 3]

a.put_after(2, 4)
a # => [1, 2, 4, 3]

Raises:

  • (ArgumentError)


27
28
29
30
31
# File 'lib/ramaze/snippets/array/put_within.rb', line 27

def put_after(element, object)
  return self[index(element) + 1, 0] = object if include?(element)

  raise ArgumentError, "The given element doesn't exist"
end

#put_before(element, object) ⇒ Object

a = [1, 2, 3]

a.put_before(2, 4)
a # => [1, 4, 2, 3]

Raises:

  • (ArgumentError)


37
38
39
40
41
# File 'lib/ramaze/snippets/array/put_within.rb', line 37

def put_before(element, object)
  return self[rindex(element), 0] = object if include?(element)

  raise ArgumentError, "The given element doesn't exist"
end

#put_within(object, constrain) ⇒ Object

a = [1, 2, 3]

a.put_within(4, :after => 2, :before => 3)
a # => [1, 2, 4, 3]

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
# File 'lib/ramaze/snippets/array/put_within.rb', line 15

def put_within(object, constrain)
  pre, post = constrain.values_at(:after, :before)

  return put_after(pre, object) if rindex(post) - index(pre) == 1

  raise ArgumentError, "Too many elements within constrain"
end