Ruby Method of the Day - Array.reject!

Posted by Kelly McCauley on Nov 21, 2007

Signature

array.reject! {|element| block}  #=> array or nil

array.reject {|element| block} does the exact same thing as Array.delete_if except that it returns nil if no changes were made to array.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

b = a.clone                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b.reject! {true}            #=> []
b                           #=> []

b = a.clone                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b.reject! {false}           #=> nil
b                           #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

b = a.clone                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b.reject! {|n| n == 3}      #=> [1, 2, 4, 5, 6, 7, 8, 9, 10]
b                           #=> [1, 2, 4, 5, 6, 7, 8, 9, 10]

b = a.clone                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b.reject! {|n| n % 2 == 0}  #=> [1, 3, 5, 7, 9]
b                           #=> [1, 3, 5, 7, 9]

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.reject!

Ruby Method of the Day - Array.reject

Posted by Kelly McCauley on Nov 20, 2007

Signature

array.reject {|element| block}    #=> new_array

array.reject {|element| block} iterates over array’s elements and returns new_array that contains any element in array where the block returns either nil or false.

Examples

1
2
3
4
5
6
7
8
9
10
11
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a.reject {|n| nil}                        #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.reject {|n| false}                      #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.reject {|n| true}                       #=> []
a.reject {|n| ''}                         #=> []
a.reject {|n| 0}                          #=> []

a.reject {|n| n == 3}                     #=> [1, 2, 4, 5, 6, 7, 8, 9, 10]
a.reject {|n| n % 2 == 0 }                            #=> [1, 3, 5, 7, 9]
a.reject {|n| true if (n % 3 == 0) || (n % 5 == 0) }  #=> [1, 2, 4, 7, 8]

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.reject

Ruby Method of the Day - Array.last

Posted by Kelly McCauley on Nov 19, 2007

Signature

array.last            #=> object or nil
array.last(number)    #=> new_array

array.last returns the last element of array or it returns nil if array is empty. array.last(number) returns the last number elements of array or it returns an empty array if array is empty.

Examples

1
2
3
4
5
6
7
8
9
10
a = ["a", "b", "c", "d", "e", "f"]

a.last        #=> "f"
[].last       #=> nil

a.last(0)     #=> []
a.last(1)     #=> ["f"]
a.last(4)     #=> ["c", "d", "e", "f"]
a.last(99)    #=> ["a", "b", "c", "d", "e", "f"]
[].last(10)   #=> []

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.last

Ruby Method of the Day - Array.first

Posted by Kelly McCauley on Nov 16, 2007

Signature

array.first           #=> object or nil
array.first(number)   #=> new_array

array.first returns the first element of array or it returns nil if array is empty. array.first(number) returns the first number elements of array or it returns an empty array if array is empty.

Examples

1
2
3
4
5
6
7
8
9
10
a = ["a", "b", "c", "d", "e", "f"]

a.first           #=> "a"
[].first          #=> nil

a.first(0)        #=> []
a.first(1)        #=> ["a"]
a.first(99)       #=> ["a", "b", "c", "d", "e", "f"]
[].first(10)      #=> []

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.first

Ruby Method of the Day - Array.fetch

Posted by Kelly McCauley on Nov 15, 2007

Signature

array.fetch(position)             #=> object

array.fetch(position) returns the object located at position. If position is outside array an IndexError is thrown. Note that if position is negative and outside of array then the index number reported in the exception will be reported as position - array.length. I’ve submitted a patch to fix it. If position is 0 or positive then start counting from the beginning of the array. If position is negative then start counting from the end of the array.

array.fetch(position, default)    #=> object

array.fetch(position, default) returns the object located at position. If position is outside of array then default is returned. If position is 0 or positive then start counting from the beginning of the array. If position is negative then start counting from the end of the array.

array.fetch(position) {|position| block}  #=> object

array.fetch(position) {|position| block} returns the object located at position. If position is outside of array then block’s returned results is returned. If position is 0 or positive then start counting from the beginning of the array. If position is negative then start counting from the end of the array.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
a = ['a','b','c','d','e','f']   #=> ["a", "b", "c", "d", "e", "f"]
a.fetch(2)                      #=> "c"
a.fetch(-2)                     #=> "e"

begin
  a.fetch(99)
rescue Exception => e
  e.inspect                     #=> "#<IndexError: index 99 out of array>"
end

begin
  a.fetch(-99)
rescue Exception => e
  # Note that it reports an index of -93 (i.e. -99 - a.length).
  e.inspect                     #=> "#<IndexError: index -93 out of array>"
end


begin
  a.fetch(-7)
rescue Exception => e
  # Note that it reports an index of -1 (i.e. -7 - a.length).
  e.inspect                     #=> "#<IndexError: index -1 out of array>"
end


a.fetch(4, 'z')                 #=> "e"
a.fetch(99, 'z')                #=> "z"

a.fetch(4){false}               #=> "e"
a.fetch(99){false}              #=> false

def default_fetch(ary, position)
  element = nil
  if position > ary.length
    element = ary.last
  else
    element = ary.first
  end
end

a.fetch(99){|position| default_fetch(a, position)}    #=> "f"
a.fetch(4){|position| default_fetch(a, position)}     #=> "e"
a.fetch(-99){|position| default_fetch(a, position)}   #=> "a"

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.fetch

Ruby Method of the Day - Array.delete_if

Posted by Kelly McCauley on Nov 14, 2007

Signature

array.delete_if {|element| block}   #=> array

array.delete_if {|element| block} iterates over all elements of array and deletes an element from array if block returns true for that element.

Examples

1
2
3
a = [1,2,3,4,5,6,7,8,9,10]    #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.delete_if {|n| n % 2 == 0}  #=> [1, 3, 5, 7, 9]
a                             #=> [1, 3, 5, 7, 9]

The following is another usage example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env ruby
#
# A contrived example of using Array.delete_if
#

$VERBOSE = true

require 'pp'

# Member of an organization.
class Member
  attr_accessor :name
  attr_accessor :current
  def current?
    @current
  end
end


# Raw member data
members_data = [
  ['Bob', true],
  ['Fred', false],
  ['Bill', false],
  ['Alice', true]
]

# Create the members based on the raw member data
members = members_data.map do |entry|
  member = Member.new
  member.name = entry[0]
  member.current = entry[1]
  member
end

puts 'Before purging of non-current members...'
pp members
puts "\n"

# Purge non-current members.
members.delete_if {|member| !member.current?}

puts 'After purging of non-current members...'
pp members


Produces…

Before purging of non-current members...
[#<Member:0x87780 @current=true, @name="Bob">,
 #<Member:0x877a8 @current=false, @name="Fred">,
 #<Member:0x87794 @current=false, @name="Bill">,
 #<Member:0x8776c @current=true, @name="Alice">]

After purging of non-current members...
[#<Member:0x87780 @current=true, @name="Bob">,
 #<Member:0x8776c @current=true, @name="Alice">]

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.delete_if

Ruby Method of the Day - Array.delete

Posted by Kelly McCauley on Nov 13, 2007

Signature

array.delete(object)                #=> object or nil
array.delete(object) {|o| block }   #=> object or returned_block_result

array.delete(object) removes all occurances of object from array and returns object if object is found in array or it returns nil if object is not found in array. If block is given and object is not found in array then the the block’s returned results is returned by array.delete.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a = [1,2,3,4,5,6,7]       #=> [1, 2, 3, 4, 5, 6, 7]
a.delete(7)               #=> 7
a                         #=> [1, 2, 3, 4, 5, 6]
a.delete('foo')           #=> nil

a = [7,1,2,3,7,4,5,6,7]   #=> [7, 1, 2, 3, 7, 4, 5, 6, 7]
a.delete(7)               #=> 7
a                         #=> [1, 2, 3, 4, 5, 6]

a.delete('foo') {false}   #=> false

a.delete('foo') do |item|
  "'#{item}' not found"
end                       #=> "'foo' not found"

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.delete

Ruby Method of the Day - Array.compact and Array.compact!

Posted by Kelly McCauley on Nov 12, 2007

Signature

array.compact   #=> new_array
array.compact!  #=> array or nil

array.compact returns new_array that contains all non-nil elements in array (nil elements removed). array.compact! either returns array with all nil elements removed or returns nil if no nil elements were removed.

Examples

1
2
3
4
5
6
a = [1, nil, nil, 4, nil]       #=> [1, nil, nil, 4, nil]
a.compact                       #=> [1, 4]
a                               #=> [1, nil, nil, 4, nil]
a.compact!                      #=> [1, 4]
a                               #=> [1, 4]
a.compact!                      #=> nil

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.compact, Array.compact!

Ruby Method of the Day - Array.pop

Posted by Kelly McCauley on Nov 09, 2007

Signature

array.pop   #=> object or nil

array.pop removes and returns the last object from array. nil is returned if array is empty (which is not a good test for an empty array since the last object of the array could itself be nil).

Examples

1
2
3
4
5
6
7
stack = []
stack.pop           #=> nil
stack.push(1,2,3)   #=> [1, 2, 3]
stack.pop           #=> 3
stack               #=> [1, 2]
stack.push(nil)     #=> [1, 2, nil]
stack.pop           #=> nil

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.pop

Ruby Method of the Day - Array.nitems

Posted by Kelly McCauley on Nov 08, 2007

Signature

array.nitems    #=> integer

array.nitems returns the number of non-nil elements contained in array.

Examples

1
2
3
4
5
6
a = [1, 2, 3, 4, 5]
a.nitems                    #=> 5
a = [1, nil, nil, 4, nil]
a.nitems                    #=> 2
a = [nil, nil, nil, nil]
a.nitems                    #=> 0

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.nitems

Older posts: 1 2 3 ... 7