Search code examples
rubysymbols

What does :this means in Ruby on Rails?


I'm new to the Ruby and Ruby on Rails world. I've read some guides, but i've some trouble with the following syntax. I think that the usage of :condition syntax is used in Ruby to define a class attribute with some kind of accessor, like:

class Sample
  attr_accessor :condition
end

that implicitly declares the getter and setter for the "condition" property. While i was looking at some Rails sample code, i found the following examples that i don't fully understand.

For example:

@post = Post.find(params[:id])

Why it's accessing the id attribute with this syntax, instead of:

@post = Post.find(params[id])


Or, for example:

@posts = Post.find(:all) 

Is :all a constant here? If not, what does this code really means? If yes, why the following is not used:

@posts = Post.find(ALL)

Thanks


Solution

  • A colon before text indicates a symbol in Ruby. A symbol is kind of like a constant, but it's almost as though a symbol receives a unique value (that you don't care about) as its constant value.

    When used as a hash index, symbols are almost (but not exactly) the same as using strings.

    Also, you can read "all" from :all by calling to_s on the symbol. If you had a constant variable ALL, there would be no way to determine that it meant "all" other than looking up its value. This is also why you can use symbols as arguments to meta-methods like attr_accessor, attr_reader, and the like.

    You might want to read up on Ruby symbols.