syntax - Why sometimes Ruby mistakes hash literals with blocks -
this works:
[1, 2].inject({}) |result, item| end this works:
[1, 2].inject hash.new |result, item| end this throws syntaxerror:
[1, 2].inject {} |result, item| end in cases hash literal {} , hash.new not interchangeable?
any method may called optional block. a block may have form do |params| ... end or form { |params| ... } it idiomatic within ruby community utilize former multiline blocks , latter single-line blocks. blocks not have take parameters, in case can appear either do ... end or { ... }. thus foo {} interpreted either method taking empty hash argument, i.e. foo({}) or method beingness passed empty block, similar foo{ |x| } or foo{ nil }. ruby opts interpret former, leaves illustration method taking 2 blocks, not syntactically valid.
since seem not aware of more terse block syntax, utilize so:
squares = [1,2,3,4,5].map{ |x| x*x } #=> [1,4,9,16,25] and here's (not-very useful) illustration of legal empty block syntax:
p [1,2,3].map{} #=> [nil,nil,nil] the block has no statements, , value of lastly look in block nil, each value in block mapped.
ruby syntax
No comments:
Post a Comment