Ruby Objects and Dot Syntax
Coming from JavaScript I’m very accustomed to doing something like this:
var person = { name: 'Rob', city: 'San Francisco' }
console.log( person.city ); // 'San Francisco'
Using dot syntax to access a Hash
is second nature to me. That’s why I was surprised when I ran into the following error yesterday while writing some Ruby.
person = {name: 'Rob', city: 'San Francisco'}
=> {:name=>"Rob", :city=>"San Francisco"}
puts person.city
NoMethodError: undefined method `city' for {:name=>"Rob", :city=>"San Francisco"}:Hash
“Hmm, weird,” I thought. I know I’ve seen dot syntax used in Ruby before..what gives?