Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ?

share|improve this question
    
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. – Kyle Smith May 6 '14 at 17:54

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.

share|improve this answer

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.

share|improve this answer
4  
Please expand this answer a bit, to explain why a syntax is cleaner with such or such version of Ruby. – Mat's Mug May 6 '14 at 14:39
    
@Mat'sMug edited. – mohamagdy May 7 '14 at 13:56
    
I Added "cleaner in terms of readability" – mohamagdy May 7 '14 at 14:03

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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