2
\$\begingroup\$

I am writing some code in Ruby on Rails to Create an object.

I am using Ruby 2.0 and Rails 4.0.3 in my Application.

I have a Model called:

class GroupUsers < ActiveRecord::Base
  belongs_to :users
  belongs_to :group

This is basically a ManyToMany mapping between Users and Groups. So, today I was creating an object for this Model.

But I found out I could follow two syntax for this, as follows

GroupUsers.create( :user => user, :group => group )

Or

GroupUsers.create( user: user, group: group )

Basically since this is related to creating a Hash so it must be a question of the best practice in Ruby.

Which syntax should be preferred ?

\$\endgroup\$
1
  • \$\begingroup\$ I suggest adopting a style guide appropriate to the Ruby version of your project and adhering to that. ruby-style-guide enforces Ruby 1.9 style hash syntax for Ruby 1.9+ projects, for example. \$\endgroup\$
    – Kyle Smith
    May 6, 2014 at 17:54

3 Answers 3

3
\$\begingroup\$

It depends. I prefer the newer syntax because I feel that it is more readable. As others have pointed out, however, the newer syntax is only compatible with Ruby 1.9.2+.

You should be aware, however, that the new syntax does not entirely replace the hash rocket syntax. This is because you can only use the newer syntax with symbols.

{ "text": :hello } #=> syntax error, unexpected ':', expecting =>

If you want to use strings and methods, you will still need to use the has rocket:

{ method_name => :hello }
{ "a_string" => :hello }

Personally, from my experience of reading and watching educational materials, the newer syntax is preferred where possible. It's also less keystrokes: : instead of => is easier for me.

\$\endgroup\$
0
\$\begingroup\$

Depends on the Ruby version you're using. If you're using Ruby 1.9.2+ then the second syntax is cleaner in terms of readability.

If you're using Ruby 1.8 then you can't use the second syntax anyway and you have not choice.

\$\endgroup\$
3
  • 4
    \$\begingroup\$ Please expand this answer a bit, to explain why a syntax is cleaner with such or such version of Ruby. \$\endgroup\$ May 6, 2014 at 14:39
  • \$\begingroup\$ @Mat'sMug edited. \$\endgroup\$
    – mohamagdy
    May 7, 2014 at 13:56
  • \$\begingroup\$ I Added "cleaner in terms of readability" \$\endgroup\$
    – mohamagdy
    May 7, 2014 at 14:03
0
\$\begingroup\$

Well, you can also create an ActiveRecord object with a block passed:

GroupUsers.create do |gu|
  gu.user = user
  gu.group = group
end

though I don't think it's suitable with just a few attributes being set. However, I'd suggest renaming the robot-like GroupUsers into Membership, for example.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.