Last active
December 21, 2015 02:38
-
-
Save davidbalbert/6235918 to your computer and use it in GitHub Desktop.
Syntax idea: conditionals in hash literals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If the conditionals evaluate to false, the key wouldn't be present in the hash | |
Person.new( | |
first_name: params[:first_name], | |
last_name: params[:last_name], | |
age: params[:age] if params[:age].to_i > 18, | |
bio: params[:bio] unless params[:bio].blank?) | |
# This would be equivalent to | |
person_hash = { | |
first_name: params[:first_name], | |
last_name: params[:last_name] | |
} | |
person_hash[:age] = params[:age] if params[:age].to_i > 18 | |
person_hash[:bio] = params[:bio] unless params[:bio].blank? | |
Person.new(person_hash) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks :)