ABMagil
ABMagil

Reputation: 5615

Are Parentheses Still Optional in Ruby?

If I run, per the docs

a = [:code]
a.collect { |x| x.to_s } # => ["code"]

However if I run

a = [:code]
a.collect({ |x| x.to_s }) # => SyntaxError

As far as I know, ruby has optional parens. How is my syntax getting screwed up here? This is an even bigger problem for me because I want to chain another function after this one, so I require the parens.

Upvotes: 2

Views: 405

Answers (1)

nzifnab
nzifnab

Reputation: 16092

You aren't passing the block as a parameter to the parenthesis.

a.collect { |x| x.to_s }

is the same as

a.collect() {|x| x.to_s }

is the same as

a.collect() do |x|
  x.to_s
end

And all of that is fairly close to this as well:

block = -> (x) {x.to_s}   # Shortcut 'stabby' syntax for lambda{|x| x.to_s}
a.collect(&block) # Or a.collect &block

Upvotes: 7

Related Questions