5 More Ruby Tips

Yinquan Teo

twitter: @yinquanteo
github: github.com/yinquanteo
url: yinquanteo.com

1. HTTP Server


ruby -run -e httpd . -p 8080

2. inline Heredoc 

UGLY :(
module Adding  class SomeSpace    def ugly_text      <<HERESuch ugly indentationisn't it?HERE    end  endend

2. INLINE HEREDOC 

pretty :)
module Adding  class SomeSpace    def beautiful_text      <<-HERE.strip_heredoc        Beautifully indented        isn't it?      HERE    end  endend

3. Ruby Scripting


 printf "super\nsize\nme" | ruby -ne 'puts $_.upcase'

4. URI Query PARAMS

hash to query params
require 'active_support/core_ext'params = {  scope: "read, write & profit",   url: "http://referralcandy.com"}params.to_query 
# => "scope=read%2C+write+%26+profit&url=http%3A%2F%2Freferralcandy.com"

4. URI QUERY PARAMS

query params to hash
require 'rack'query = "url=http%3A%2F%2Freferralcandy.com&scope=read%26profit"Rack::Utils.parse_nested_query(query)
# => {"url"=>"http://referralcandy.com", "scope"=>"read&profit"}

5. rescuing from exception


BAD
loop do
  begin    booom   rescue Exception => e 

endend

RESCUE HIERARCHY

 Exception
  NoMemoryError
  ScriptError
    LoadError
    NotImplementedError
    SyntaxError
  SignalException
    Interrupt
  StandardError         
    ArgumentError
    IOError
      EOFError
    IndexError
    LocalJumpError
    NameError
      NoMethodError
    RangeError
      FloatDomainError
    RegexpError
    RuntimeError
      Timeout::Error
    SecurityError
    SocketError
    SystemCallError
    SystemStackError
    ThreadError
    TypeError
    ZeroDivisionError
  SystemExit
  fatal

Good

begin  booomrescue => eend

QuESTIONS?

5 More Ruby Tips

By yinquanteo

5 More Ruby Tips

  • 1,190
Loading comments...

More from yinquanteo