James Evans
James Evans

Reputation: 795

Assignment in Ruby does not work as expected

i have this statement:

if user = params[:user] && action == :delete
end

why is user always set to :delete?

should not it be set to user name if user passed or nil otherwise.

Upvotes: 1

Views: 69

Answers (2)

Bozhidar Batsov
Bozhidar Batsov

Reputation: 56595

&& binds stronger than the assingment. You can use and instead if you're keen on omitting the parentheses:

if user = params[:user] and action == :delete
end

As a matter of style - using the return value of = (an assignment) is ok, but surround the assignment with parentheses.

  # good - shows intended use of assignment
  if (v = array.grep(/foo/)) ...

  # bad
  if v = array.grep(/foo/) ...

  # also good - shows intended use of assignment and has correct precedence.
  if (v = self.next_value) == 'hello' ...

The use of and and or in conditional expressions is discouraged so you're better off with the solution suggested by Ian Bishop.

Upvotes: 1

Ian Bishop
Ian Bishop

Reputation: 5205

You need to put () around the assignment in Ruby for it to be evaluated as you expect

if (user = params[:user]) && action == :delete
end

Upvotes: 3

Related Questions