Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through array and return itself

Tags:

crystal-lang

This code: p [1, 2].each{ "foo" } produces nil, whilst I want it to put [1, 2] after iteration. How-to in Crystal?

like image 853
Vlad Faust Avatar asked Feb 11 '26 10:02

Vlad Faust


1 Answers

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]
like image 65
Vitalii Elenhaupt Avatar answered Feb 16 '26 17:02

Vitalii Elenhaupt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!