Syntax Notes

  • ARRAY: 
    • unshift - push (prepend and append)
    • shift - pop, delete (remove first and last element, delete any elements)
    • sort - sort.reverse
    • take(n) : getting n first elements <> drop(n)
    • include?(n)
    • a.insert(1,100) => [1, 100, 2, 3, 4, 5, 6, 7, 8, 9]
    • compact => remove all nil values.
    • reverse_each
    • arr = [1, 2, 3, 4, 5, 6] 
      • arr.select { |a| a >]]> 3 }     #=> [4, 5, 6]
      • arr.reject { |a| a < 3 }     #=> [3, 4, 5, 6]
      • arr.drop_while { |a| a < 4 } 
      • arr.delete_if { |a| a < 4 } #=> [4, 5, 6] 
      • arr.keep_if { |a| a < 4 } #=> [1, 2, 3] 
    • [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]                 #=> [ 1, 3 ] 
    • [ 1, 2, 3 ] * 3    #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] 
    • [ 1, 2, 3 ] + [ 4, 5 ]    #=> [ 1, 2, 3, 4, 5 ] 
    • a = [1, 2, 3, 4] 
      • a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] 
      • a.delete_at(1) => [1,3,4]
  • STRING: 
    • ord - chr
    • chars (string to arrays of chars)
    • chomp <> chomp("llo") (remove ending char like "\n" <> "hello".chomp("llo") => "he")
    • "hello".chop  => "hell" (always remove one last char)
    • "hello".chr     => "h" (return first char)
    • "hello".clear  => ""
    • upcase <> downcase
    • "ab".each_byte {|c| print c, ' ' }
      • 97 98 => "ab"
    • "hello".each_char {|c| print c, ' ' }
      • h e l l o => "hello"
    • include? 
    • index("a")
    • replace("abc")
    • insert(0,"x")
    • "hello".intern => :hello
    • " hello".lstrip => "hello" <> chop == rstrip => strip (remove both leading and trailing whitespace)
    • "hello".start_with?("hell")   => true
    • camelize => "truong" -> "Truong"
  • HASH
    • Just keep the valid elements based on keys
      • { a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b) # => {:a=>1, :b=>2} 
      • valid_keys = [:mass, :velocity, :time] => options.slice(*valid_keys). Pay attention on "*"[array of keys]
  • Date
    • 7.days.from_now
  • JSON
    • Transferring json via form post: 
      • firstly using JSON.generate to make sure it's correct format before put it into hidden_field_tag
      • next JSON.parse to get json format in order to use in controller.
    • distinguishing json from hash: { } is hash, not json.
    • String keys to symbol:
    • JSON.parse(s,:symbolize_names => true)