Skip to content

Instantly share code, notes, and snippets.

@gogojimmy
Created October 19, 2015 11:09
Show Gist options
  • Save gogojimmy/d187fb57d9f55a62016d to your computer and use it in GitHub Desktop.
Save gogojimmy/d187fb57d9f55a62016d to your computer and use it in GitHub Desktop.
  1. 一般 Hash 情況是這樣:
hash = {}
hash[:foo][:bar] = :hello
=> NoMethodError: undefined method `[]=' for nil:NilClass

請建立一個 Hash 可以不管 key 值是否存在都可以自動設定 key 及 value

例如說以上的例子就會是

hash = Hash.new(//實作)
hash[:foo][:bar] = :hello
hash
=> { :foo => { :bar => :hello } }
  1. 想像一個 controller, 依照使用者的 role 來判斷來 redirect 到不同的路徑:
if user_signed_in?
  if current_user.role == "admin"
    redirect_to admin_path
  elsif current_user.role == "reviewer"
    redirect_to reviewer_path
  elsif current_user.role == "collaborator"
    redirect_to collaborator
  else
    redirect_to user_path
  end
else
  render :new
end 

有什麼更漂亮的做法來避免如此的巢狀 if else

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment