alex_milhouse alex_milhouse - 3 months ago 8
Ruby Question

What is the difference between :to and => in rails

I have been noticing that the rails community has been moving towards using the ":" notation for more things. And now recently I received a comment in a code review that this:

post 'examples/', to: 'examples#index'


was better than this:

post "examples/" => "examples#index"


My questions are:


  1. Is there a difference between these two statements?

  2. If so why is one better than the other?

  3. Why is the rails community switching to the ":" notation (or are they)?

  4. Moving forward with rails 4 and soon 5, are both formats still acceptable?


Answer

In context of Rails routes:

  • Is there a difference between these two statements?

There is no difference.

  • If so why is one better than the other?

No, it's the same.

  • Why is the rails community switching to the ":" notation (or are they)?

Just a more readable, 'from' => 'to' and 'from', to: 'to'

  • Moving forward with rails 4 and soon 5, are both formats still acceptable?

Yes.

The => notation it's a hash ruby feature, and related to the :symbol. You can write symbols by two ways :key => value and key: value.