Class: Hash

Inherits:
Object show all
Defined in:
lib/roebe/core/hash.rb

Overview

#

x=“a”=>2,“b”=>3;x.rand

#

Instance Method Summary collapse

Instance Method Details

#randObject

#

rand

random key

#


32
33
34
# File 'lib/roebe/core/hash.rb', line 32

def rand
  self[self.keys.rand]
end

#sort_by_alphabeticalObject Also known as: sort_alphabetically

#

sort_by_alphabetical

Will put numerical values at the end.

$hash.sort_by_alphabetical

=> ["a", "b", "z", "2", "4", "33"]
#


44
45
46
# File 'lib/roebe/core/hash.rb', line 44

def sort_by_alphabetical
  self.sort_by { |s| [ s.to_i, s.downcase ] }
end

#to_struct(name_of_new_struct) ⇒ Object

#

to_struct

Usage example:

 x={"name"=>"Joe Smith", "zip"=>12345, "address"=>["123 Maple", "Anytown NC"]}.to_struct(:Customer)
#<struct Customer name="Joe Smith", zip=12345, address=["123 Maple", "Anytown NC"]>
#


20
21
22
23
24
25
# File 'lib/roebe/core/hash.rb', line 20

def to_struct(name_of_new_struct)
  Object.const_set(name_of_new_struct, Struct.new(*self.keys.map {|k| k.to_sym}))
  object = Module.const_get(name_of_new_struct).new
  self.each { |k,v| object[k] = v }
  object
end