Skip to content

Instantly share code, notes, and snippets.

@devonestes
Created December 4, 2014 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devonestes/f1f342152a6b6bca19f4 to your computer and use it in GitHub Desktop.
Save devonestes/f1f342152a6b6bca19f4 to your computer and use it in GitHub Desktop.
# When we're working with validations in AR, remember that most of them are accepting hashes as arguments.
# For example, we could re-write
validates :email, { :uniqueness => true }
# as
validates(:email, { :uniqueness => true })
# which pretty clearly shows that we have two arguments for the validates method, a symbol and a hash
# Now, about that hash argument... We're currently creating it using the 'rocket' notation:
{ :uniqueness => true }
# The key in the key/value pair is the symbol ':uniqueness', and the value in the key/value pair is the
# Boolean 'true'.
# HOWEVER - we could also create the exact same hash using different notation, like below:
{ uniqueness: true }
# The different notation just says "Hey, Ruby, can you take this first thing ('uniqueness'), turn it into a symbol,
# and then make that symbol the key for this key/value pair? Oh, and could you also be awesome and make that second
# thing ('true') the value for this key/value pair? Thanks!"
# So basically if we write:
{ uniqueness: true }
# Ruby is super nice to us and turns it into:
{ :uniqueness => true }
# However, if you really wanted a string as your key, this alternative way to create a hash would
# totally mess things up! We'd write:
{ "uniqueness": true }
# and Ruby would flip out because it doesn't know what to do! We'd get the error
syntax error, unexpected ':', expecting =>
# So, if you want to use anything other than a symbol for our key, you need to use the rocket notations for hashes!
# Here are a few examples of ways to write hahses and how Ruby would interpret our writing for further clarification:
# How we write the hash How Ruby interprets the hash
{ uniqueness: true } == { :uniqueness => true }
{ "uniqueness": true } == syntax error, unexpected ':', expecting =>
{ "uniqueness" => true } == { "uniqueness" => true }
{ 1 => true } == { 1 => true }
{ 1: true} == syntax error, unexpected ':', expecting =>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment