ruby reduce example

Example 1: ruby reduce

# Sum some numbers
(5..10).reduce(:+)                             #=> 45
# Same using a block and inject
(5..10).inject { |sum, n| sum + n }            #=> 45
# Multiply some numbers
(5..10).reduce(1, :*)                          #=> 151200
# Same using a block
(5..10).inject(1) { |product, n| product * n } #=> 151200
# find the longest word
longest = %w{ cat sheep bear }.inject do |memo, word|
   memo.length > word.length ? memo : word
end
longest                                        #=> "sheep"

Example 2: reduce ruby baud rate

# frozen_string_literal: true

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

# For each server, enqueue a worker.
servers.each do |server|
  queue.map do
    # Simulate random wait due to network communication
    sleep rand(0..3)
    puts "#{Time.now.utc} - querying: #{server}"

    # Return a result object with the name of the server and the result of the query
    OpenStruct.new(name: server, in_sync: true)
  end
end

result = queue.reduce([]) do |server, memo|
  memo << server
end

puts "in sync: #{result.in_sync?}"

Tags:

Ruby Example