Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array repeat value if next not present,

How can we achieve this in Ruby?

xs = [1,2,3]
x = 5

Then I need that sum = 1+2+3+1+2 = 9

like image 520
joe nayyar Avatar asked May 12 '26 00:05

joe nayyar


1 Answers

You have the abstractions you need in the core, just wire them together: Enumerable#cycle, Enumerable#take and Enumerable#inject:

>> [1, 2, 3].cycle.take(5).inject(0, :+)
=> 9

That's the functional/declarative approach: use abstractions (either existing or those you implement yourself) so you can write code that describes what you are doing instead of how you are doing it.

like image 101
tokland Avatar answered May 14 '26 13:05

tokland



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!