Reduce in Ruby

All
For numbers
array = [1,2,3,4,5,6,7,8,9,10]
puts array.reduce(:+) #very simplified
puts array.reduce(0,:+)
puts array.reduce(1,:+)
puts array.reduce(10,:+)
puts array.reduce(100,:+)
puts array.reduce(-1,:+)

 

For strings

array = [“say”, “my”,”name”,”say”,”my”,”name”]
puts array.reduce(:+)
puts array.reduce(“mario”,:+)
Output:
55
55
56
65
155
54
saymynamesaymyname
mariosaymynamesaymyname

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s