switch

  def switch(data)
    switched_data = data.class.new
    switch_proc = lambda do |a, b|
      switched_data << b unless b.nil? and data.is_a?(String)
      switched_data << a
    end
    if data.is_a?(String)
      data.to_enum(:each_byte).each_slice(2) { |a, b| switch_proc.call(a, b) }
    else
      data.each_slice(2) { |a, b| switch_proc.call(a, b) }
    end
    switched_data
  end

 

具体示例:

 

    p switch("foo!")        # => "of!o"
    p switch((1..10).to_a)  # => [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]

 

你可能感兴趣的:(switch)