Ruby &: syntax method

I ran into an error where I forgot a space like this

@entries = [#<Entry id: 3806, approved: false, submitted: false] @entries.any?&:submitted? => true @entries.any? &:submitted? => false 

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

+4
source share
1 answer

The problem is that it is also a Unary operator that takes precedence.

When you do this:

 @entries.any?&:submitted? 

In fact, you are doing the following:

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

The result is true. Since @entries has entries and the symbol: sent? has true true.

When you do this:

 @entries.any? &:submitted? 

What you are actually doing is:

 @entries.any?(&:submitted?) 

This is what you really want.

The reason @pilcrow made it work is because he used 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 

PS: Same thing with @ fl00r example:

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

[1,2, zero] .Any? leads to truth and: nil? is true, so the results are the same because [1,2, nil] also contains nil, but the calculations are different.

+18
source

Source: https://habr.com/ru/post/1343039/


All Articles