/RubyEx

Handy shortcut for ruby the programming language.

Primary LanguageRuby

Edit June 14, 2017 - Due to the danger of monkey patching, only hash-ex is recommended.

hash-ex.rb:
- Addition operator added. Simply call Hash.merge

  Example:
  a = {'a'=>1}
  b = a + {'b'=>2}            #b = {'a'=>1, 'b'=>2}

- Override new method: add Hash.new(obj){|hash|...} pattern

  Example:
  hash = Hash.new(100){|h| h[:x] = 10}
                              #{:x => 10} with default value 100

string-ex.rb
- Addition operator overridden. Added String + Integer.
  If string is a char (only one character in in), string + integer will act as addition of char code.
  If string has more than one character, it will add integer literally.
  
  Example:
  'a' + 1                     #'b'
  'aa' + 1                    #'aa1'
  'aa' + 'bb'                 #'aabb'
  
- Defined String#to_proc
  Similar to Symbol#to_proc. Parameters should be written as $0,$1,$2,...
  
  Example:
  #Example 1
  foo = '$0+1'.to_proc
  foo.call(1)                 #2
  
  #Example 2
  foo = '$1**2'.to_proc
  foo[0,2]                    #4; $0 is not ignore but not in calculation
  
  #Example 3
  foo = '$0.capitalize + $1'.to_proc
  foo['hello','world']        #'Helloworld'
  
  #Example 4
  [1,2].map(&'$0+1')          #[2,3]
  
  #Example 5
  [1,2,3].inject(&'+')        #6; same as [1,2,3].inject(&:+)
  
  #Example 6
  ['hello','world'].map(&'$0.capitalize').inject(&'+')
                              #'HelloWorld'
  
  #Example 7
  [[1,2],[3,4]].map(&'+')     #[3,7]
  
  #Example 8
  [[[33,44],1],[[55,66],0]].map(&'$0[$1]').inject(&'+')
                              #99; 99 = [44,55].inject(&:+)
  
  Seperate lines of code can be divided by ';'
  #Example 9
  ['hello','world'].map(&'$0.capitalize; $0+" "')
                              #"Hello World "
  
dep-hash.rb
- A hash type with any depth can be easily assigned (vivid hash)
  dp = DepHash.new
  dp[:a][:b][:c] = 10
  dp[:a][:b][:d][:e][:f] = 100
                              #{:a=>{:b=>{:c=>10, :d=>{:e=>{:f=>100}}}}}