1

I am pretty new to Rails and I'm working with a new code base that sometimes uses two different syntax for the same thing.

class: 'item'

vs

:class => "item"

However, I have have not been able to find what the difference is or which style I should use as best-practice.

I assume that it has something to do with the Rails version. We are planning to move to Rails 6. Can somebody shed some insight on this for me?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
DigitalM0nkey
  • 127
  • 1
  • 3
  • 8

3 Answers3

1

They are the same thing, both create a key/value pair. Where the key is the Symbol :class and the value is the String 'item'.

Normally you create a key/value pair using the => syntax. {'key' => 'value'} (here both the key and value are a String) however, since a symbol already starts with a symbol they've added some syntactic sugar later on.

The : at the end of a symbol denotes both that the key is a symbol and that it concerns a key/value pair. For symbols {:key => 'value'} is the old syntax and {key: 'value'} is the newer variant. The examples given here are hash literals but this also applies when calling methods. some_method(key: 'value')

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
0

They're the same.

Consider this:

{a: 1}    # => {:a=>1}
{:a => 1} # => {:a=>1}

Use either form of assigning the value as Ruby is happy. The shorter form was added as a convenience, not because it was any better or was preferable.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
0

This question does not concern Rails, it's a pure Ruby syntax.

The basic answer is that the syntax

:class => "item"

is simply from the older version of Ruby — mainly pre-1.9.

Ruby versions 1.9 and newer all support the new syntax, which is more compact and is borrowed from the JSON format.

I noticed you used double quotes in one example and single quotes in another. In Ruby we try to use single quotes whenever we have a string without interpolation, and double quotes when we use interpolation.

Therefore both of your examples should be using single quotes.

Having said that, this is a style guide that is hotly debated. See this link for more info:

https://dockyard.com/blog/ruby/2012/02/16/single-quotes-or-double-quotes