mqj

Random Elements

Posted by mqj about 1 month ago
class Array
  # returns a random element of the array
  def rand
    self[Kernel.rand(length)]
  end
end

class Hash
  # returns a random key-value pair
  def rand
    temp_key = self.keys.rand
    [temp_key, self[temp_key]]
  end
end

module Kernel
  # random_n_digit_number(1) returns a number between 1 and 9 inclusive
  # random_n_digit_number(3) returns a number between 100 and 999 inclusive
  def random_n_digit_number(n)
    raise ArgumentError, "expected digit length to be greater or equal to 1, received #{n.inspect}" if !n.is_a?(Numeric) || n < 1
    return rand(10) if n == 1
    min = 10**(n-1)
    max = (10**n)-1
    rand(max-min+1) + min
  end
end

class Range
  # (1..10).rand returns a number between 1 and 10 inclusive
  # (1...10).rand returns a number between 1 and 9 inclusive
  # (2..2).rand returns 2
  # (2...2).rand is equivalent to 2 + Kernel.rand()
  # (Date.parse('2008-08-01')..Date.parse('2008-08-31')).rand returns a date between the first and last dates 
inclusive
  # (Time.now..(Time.now+60)).rand returns a time between the first and last times inclusive
  def rand
    self.first + Kernel.rand(self.last - self.first + (self.exclude_end? ? 0 : 1))
  end
end

Create a Hash from an Array object

Posted by mqj about 1 month ago
>> a = [1,2,3,4,5,6,7,8,9,10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> Hash[ *a ]
=> {5=>6, 1=>2, 7=>8, 3=>4, 9=>10}
>> 
?>   b = [ [1,2], [3,4], 5, 6, 7, 8, 9, 10 ]
=> [[1, 2], [3, 4], 5, 6, 7, 8, 9, 10]
>> Hash[ *b ]
=> {5=>6, [1, 2]=>[3, 4], 7=>8, 9=>10}
Language Ruby / Tagged with hash, array

Create a Hash from two Array objects

# Requires Ruby 1.8.7 or higher.

>> keys = [1,2,[3,4]]
=> [1, 2, [3, 4]]
>> values = ['a','b',['c','d']]
=> ["a", "b", ["c", "d"]]
>> Hash[ * keys.zip(values).flatten(1) ]
=> {1=>;"a", [3, 4]=>["c", "d"], 2=>"b"}
Language Ruby / Tagged with hash, array, arrays, zip

Create a Date object from a Date inspect

Posted by mqj 3 months ago
# Seeing things like "<Date: 4909275/2,0,2299161>" in logs gives no immediate 
# clue what that date is.  Now one can use Date.new_from_inspect to see what date the 
# inspect string represents.


>> Date.new_from_inspect('#<Date: 4909275/2,0,2299161>').to_s
=> "2008-06-20"
>> Date.new_from_inspect(Date.today.inspect) == Date.today
=> true


class Date
  def self.new_from_inspect(date_inspect_string)
    args = date_inspect_string.split(/[^\d]/).reject{|s| s.empty?}.map{|s| s.to_i}
    new!( Rational(*args.first(2)), *args.last(2) )
  end
end
Language Ruby / Tagged with date, inspect