4

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.

2
  • Works for me, 1.8 and 1.9, with a trivial class Entry; def submitted?; true end end. Can we see the smallest possible code you have that reproduces the issue? Commented Mar 9, 2011 at 17:23
  • 1.8.7 REE works great with spave and without space [1,2,nil].any?&:nil? and [1,2,nil].any? &:nil? Commented Mar 9, 2011 at 17:32

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Aha! Great answer. Had me scratching my head, even though it seems so obvious now.
ahh, that makes so much more sense! Thank you!
what is the difference b/w & and && though
&& is the comparison operator. & is the unary/binary operator. For example 60 & 13 = 12 since (0011 1100 & 0000 1101 = 0000 1100).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.