Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Ping a range of IP addresses

(1..254).each {|i| puts ": found 192.168.1.#{i}" if  `ping 192.168.1.#{i} -c 1 -w 1`.match(/ttl/) }

Convert Ruby Array to Ranges

# Array#to_ranges
# Converts an array of values (which must respond to #succ) to an array of ranges. For example,
# [3,4,5,1,6,9,8].to_ranges => [1,3..6,8..9]

class Array
  def to_ranges
    array = self.compact.uniq.sort
    ranges = []
    if !array.empty?
      # Initialize the left and right endpoints of the range
      left, right = self.first, nil
      array.each do |obj|
        # If the right endpoint is set and obj is not equal to right's successor 
        # then we need to create a range.
        if right && obj != right.succ
          ranges << Range.new(left,right)
          left = obj
        end
        right = obj
      end
      ranges << Range.new(left,right)
    end
    ranges
  end
end

Collapse ranges in arrays

Takes an Array and turns consecutive integers into Range objects.

class Array
    def collapse_ranges
        return self if self.length <= 2
        self.uniq!
        self.sort! rescue nil
        temp_array, return_array = [], []
        self.each_with_index do |item, i|
            if item.respond_to?(:next)
                temp_array.push item
                if item.next != self[i + 1]
                    return_array.concat 3 <= temp_array.length ?
                        [temp_array.first..temp_array.last] :
                         temp_array
                    temp_array.clear
                end
            else
                return_array.concat 3 <= temp_array.length ?
                    [temp_array.first..temp_array.last] :
                     temp_array
                temp_array.clear
                return_array.push item
            end
        end
        return return_array
    end
end


>> [1, 3, 4, 5, 7, 8].collapse_ranges.join(', ')
=> 1, 3..5, 7, 8
>> %w(a c d e g i j).collapse_ranges.join(', ')
=> a, c..e, g, i, j
>> [1, 2.5, 3, 4, 5].collapse_ranges.join(', ')
=> 1, 2.5, 3..5
>> [1, 2, 3, 4, {:test => 'value'}, 5].collapse_ranges.join(', ')
=> 1..4, testvalue, 5

Ruby: make ranges always include the last value

So, in conjunction with other snipped about setting up intervals on Time, this can be added to Range to make sure it always includes the last value, even if the interval doesn't directly land you on the end value

class Range
  def each(options = {}, &block)
    val = self.begin
    while val < self.end
      yield val
      val = val.succ
    end
    yield self.end if self.end == val || options[:always_include_last]
  end
end

Find missing array items

This works fine for integers and letters. It should work for anything though, so long as Ruby can form an range from the first and last array items.

class Array
    def missing_items
        return [] if self.length <= 1
        self.uniq!
        self.sort! rescue nil
        begin
            (self.first..self.last).to_a - self
        rescue
            []
        end
    end
end


>> [1, 3, 4, 10].missing_items.join(', ')
=> 2, 5, 6, 7, 8, 9
>> [1, 2, 7, 7.5, 8.2].missing_items.join(', ')
=> 3, 4, 5, 6, 8
>> %w(a b c f g j).missing_items.join(', ')
=> d, e, h, i
>> [2.5, {:test => 'value'}].missing_items.join(', ')
=>

A range function with float increment

Taken from Edvard Majakari's comment in this recipe.

def arange(start, stop=None, step=None):
    if stop is None:
        stop = float(start)
        start = 0.0
    if step is None:
        step = 1.0
    cur = float(start)
    while cur < stop:
        yield cur
        cur += step

For python 2.2 (e.g. pys60) you need to do a "from __future__ import generators" first.
To get the list from the generator, use list(arange(...))
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS