Quantcast
Viewing latest article 33
Browse Latest Browse All 42

Answer by Ja͢ck for join enumerable to produce string in Ruby

The code within your question is already as optimal as it gets, but it's possible to remove the condition inside your block:

e = ('a'..'z').to_enumjoined_string = e.reduce { |acc, str| acc << ' some separator '<< str }.to_s

Without passing an argument to #reduce, the first time the block gets called, acc and str would represent the first two elements of the enumerable. The additional .to_s at the end is to ensure that an empty string is returned if the enumerable is empty.


Viewing latest article 33
Browse Latest Browse All 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>