Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/arrayextension.rb

Overview

The Ruby class Array is extended with a few useful methods.

Instance Method Summary collapse

Instance Method Details

#draw(number_of_elements = 1) ⇒ Object

Returns an array containing elements choosen at random

[].draw                     #=> []
[].draw(2)                  #=> []
["a"].draw(2)               #=> ["a", "a"]
["a", "b", "c"].draw        #=> ["b"] assuming "b" was choosen randomly
["a", "b", "c"].draw(2)     #=> ["b", "c"] assuming "b" and "c" were choosen randomly


34
35
36
37
# File 'lib/arrayextension.rb', line 34

def draw(number_of_elements = 1)
  return [] if empty?
  (1..number_of_elements).to_a.map { random_element }
end

#join_cr ⇒ Object

Returns a string created by converting each element of the array to a string, separated by \n

[].join_cr                  #=> ""
["a"].join_cr               #=> "a"
["a", "b", "c"].join_cr     #=> "a\nb\nc\n"


22
23
24
# File 'lib/arrayextension.rb', line 22

def join_cr
  self.compact.reject { |element| element.to_s.empty? || element.to_s.strip == "\n" }.join("\n")
end

#not_include?(element) ⇒ Boolean

Return true if element is not include in the list

[].not_include?(1) # => true [1].not_include?(1) # => false

Returns:

  • (Boolean)


44
45
46
# File 'lib/arrayextension.rb', line 44

def not_include?(element)
  !self.include?(element)
end

#to_symbols ⇒ Object

Returns an array of symbols corresponding to the elements in the array

[].to_symbols # => [] %w(collect map sort).to_symbols # => [:collect, :map, :sort] [1,2,3,4,5].to_symbols # => [:"1", :"2", :"3", :"4", :"5"] ['1', nil].to_symbols # => [:'1']



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

def to_symbols
  self.compact.collect {|element| element.to_s.to_sym }
end