ruby reduce example
Example 1: ruby reduce
(5..10).reduce(:+)
(5..10).inject { |sum, n| sum + n }
(5..10).reduce(1, :*)
(5..10).inject(1) { |product, n| product * n }
longest = %w{ cat sheep bear }.inject do |memo, word|
memo.length > word.length ? memo : word
end
longest
Example 2: reduce ruby baud rate
require "ostruct"
class MyQueue
class Worker
def initialize(&blk)
@blk = blk
end
def call
@blk.call
end
end
class Result
def initialize(merged)
@merged = merged
end
def in_sync?
@merged.all?(&:in_sync)
end
end
def initialize
@workers = []
end
def map(&blk)
@workers << Worker.new(&blk)
end
def reduce(accumulator)
merged = @workers.each_with_object(accumulator) do |worker, acc|
yield worker.call, acc
end
Result.new(merged)
end
end
servers = %w[server1.test server2.test server3.test]
queue = MyQueue.new
servers.each do |server|
queue.map do
sleep rand(0..3)
puts "#{Time.now.utc} - querying: #{server}"
OpenStruct.new(name: server, in_sync: true)
end
end
result = queue.reduce([]) do |server, memo|
memo << server
end
puts "in sync: #{result.in_sync?}"