This code: p [1, 2].each{ "foo" }
produces nil
, whilst I want it to put [1, 2]
after iteration. How-to in Crystal?
Use tap
:
p [1, 2].tap &.each { "foo" } # => [1, 2]
It yields self to the block and then returns self.
Another option (not preferable) could be creating a custom method that simply returns self after doing each:
class Array
def each_with_self
each { |x| yield x }
self
end
end
p [1, 2].each_with_self { "foo" } # => [1, 2]