The Crystal programming language | http://crystal-lang.org | Fund Crystal's development: http://is.gd/X7PRtI | Docs: http://crystal-lang.org/docs/ | API: http://crystal-lang.org/api/
Resource
is an alias to a union of other types
puts [1, 2, 3, 4, 5].reduce(0) { |acc, i| acc = acc + 1 if i.to_s =~ /3/ }
Error: undefined method '+' for Nil (compile-time type is (Int32 | Nil))
if
is making the type of acc
possibly nil
, because the return value of the block is used to set the acc
.reduce(0) { |acc, i| i.to_s =~ /3/ ? acc + i : acc }
Thanks @Blacksmoke16 your solution works, even though
puts [1, 2, 3, 4, 5].reduce(0) { |acc, i| i.to_s =~ /3/ ? acc + i : acc }
is a bit harder to read than
puts [1, 2, 3, 4, 5].reduce(0) { |acc, i| acc = acc + 1 if i.to_s =~ /3/ }
but ok I guess that's the price to pay for a compiled language ... and shows that the transition from Ruby to Crystal is not always that easy.
acc + i
instead of acc + 1
, so are all you wanting to do is count the number of time 3
is in the array?
puts [1, 2, 3, 4, 5].count 3