0

I have the following construct (simplified):

puts ['a!', 'b!', 'c?'].select { |f| f if f.end_with?('!') }

It prints

a!
b!

I want to use an ampersand to make it even shorter:

puts ['a!', 'b!', 'c?'].select(&:end_with?('!'))

But I get an error:

..., 'c?'].select(&:end_with?('!'))
                                 _
x.rb:4: syntax error, unexpected ')', expecting end-of-input

How can I solve this?

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119

1 Answers1

3

You can simplify the code a little, as:

puts ['a!', 'b!', 'c?'].select { |f| f.end_with?('!') }

You don't need the block to return the element; you just need it to return a "truthy" value.

However, as you have discovered, &:end_with?('!') is not valid ruby syntax.

There are various ways you could try to implement something clever like that, but in general I'd advise sticking to the syntax above.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77