Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby &:method syntax

I ran into a bug where i left out a space like this

@entries = [#<Entry id: 3806, approved: false, submitted: false]

@entries.any?&:submitted? => true
@entries.any? &:submitted? => false

how does the space change the behavior. Entry.submitted? => false for all the elements in the array, the second line has the desired behavior.

like image 640
loosecannon Avatar asked Dec 02 '22 03:12

loosecannon


1 Answers

The problem is that & is also a Unary Operator that has a precedence.

When you do this:

@entries.any?&:submitted?

You are actually doing is this:

(@entries.any?)&(:submitted?)

Which results in true. Since there are entries in @entries and the symbol :submitted? has a truth value of true.

When you do this:

@entries.any? &:submitted?

What you are actually doing is this:

@entries.any?(&:submitted?)

Which is what you really want.

The reason @pilcrow got his to work is that he/she was using the following class:

class Entry
  def submitted?
    true
  end
end

To reproduce the result, use the following class:

class Entry
  def submitted?
    false
  end
end

P.S: Same thing with @fl00r's example:

[1,2,nil].any?&:nil? and [1,2,nil].any? &:nil?

[1,2,nil].any? results in true and :nil? has a truth value of true, so the results are the same since [1,2,nil] also contains a nil value, but the calculations are different.

like image 159
Pan Thomakos Avatar answered Dec 30 '22 04:12

Pan Thomakos