Theo
Theo

Reputation: 45

Why do we use symbols as parameters?

Model:

class Tweet < ActiveRecord::Base
 has_one :location, dependent: :destroy
end

class Location < ActiveRecord::Base
 belongs_to :tweet
end

Controller:

class TweetsController < ApplicationController 
 def index
  @tweets = Tweet.recent.includes(:location) 
 end
end

Why do we use symbols (:location) as parameters in ruby?

Why does this not work?

@tweets = Tweet.recent.includes(location) 

Upvotes: 0

Views: 1684

Answers (2)

daino3
daino3

Reputation: 4566

It's common to use hashes passed as arguments to methods because then you don't have to worry about the ordering of arguments. Also, used quite frequently for optional arguments. Consider the examples below:

def method_with_args(name, age, dollar_amount, occupation) # gets sort of ugly and error prone
  # do something with args
end

def method_with_hash(hash = {}) # cleans up ordering and forces you to 'name' variables  
  name = hash[:name]
  age = hash[:age]
  dollar_amount = hash[:dollar_amount]
  occupation = hash[:occupation]
  # do stuff with variables
end

The second part of your question:

@tweets = Tweet.recent.includes(location)

location here is expected to be defined as a variable or method on the object that calls the method. If you run the code, the error will prompt you with that information.

In terms of hash access and performance: symbol access to a hash is about 2x faster. String access allocates a string to memory every time it's instantiated which creates a lot of garbage objects. Take a gander at this blog post

Upvotes: 0

dinomix
dinomix

Reputation: 976

Because what you are passing is essentually a string which active record will use to build a sql query. Location without the colon would be a local variable. We could possibly pass a class (Location) but a symbol is more efficient for ActiveRecord purposes. A symbol is a string which is immutable, essentialy a sort of pointer to a string so it is very efficient.

Upvotes: 1

Related Questions