Class: Array

Inherits:
Object show all
Defined in:
lib/sane/map_by.rb,
lib/sane/present.rb,
lib/sane/array_blank.rb,
lib/sane/array_contain.rb,
lib/sane/array_select_bang.rb

Instance Method Summary collapse

Instance Method Details

#map_by(method) ⇒ Object Also known as: collect_by

Returns a new array containing the results of running block once for every element in the array.

Examples:

array = ['foo', 'bar']

# No arguments
array.map_by(:capitalize) => ['Foo', 'Bar']

# With arguments and a block
array.map_by(:capitalize)

– The Array class actually has its own implementation of the map method, hence the duplication.



49
50
51
52
53
54
55
56
57
# File 'lib/sane/map_by.rb', line 49

def map_by(method)
      array  = []
      method = method.to_sym unless method.is_a?(Symbol)
      each{ |obj|
         temp = obj.send(method)
         array << temp
      }
      array
end

#map_by!(method) ⇒ Object Also known as: collect_by!

Same as Array#map, but modifies the receiver in place. Also note that a block is not required. If no block is given, an array of values is returned instead



63
64
65
66
67
68
69
70
71
72
# File 'lib/sane/map_by.rb', line 63

def map_by!(method)
   method = method.to_sym unless method.is_a?(Symbol)
   i = 0
   length = self.size
   while(i < length)
     self[i] = self[i].send(method)
     i+=1
   end
   self
end

#present?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/sane/present.rb', line 20

def present?
  length > 0
end

#select!Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/sane/array_select_bang.rb', line 2

def select!
 where_at = 0
 total = length
 each{|member|
   if yield(member)
     self[where_at] = member
     where_at += 1
   end
 }
 while(where_at < total)
   self[where_at] = nil
   where_at += 1
 end
 compact! # there may be a better way...
 self
end