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/) }
11307 users tagging and storing useful source code snippets
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
(1..254).each {|i| puts ": found 192.168.1.#{i}" if `ping 192.168.1.#{i} -c 1 -w 1`.match(/ttl/) }
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
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
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
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(', ') =>
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