Module: Polyfill::V2_4::IO::Class::Foreach::Method

Defined in:
lib/polyfill/v2_4/io/class/foreach.rb

Instance Method Summary collapse

Instance Method Details

#foreach(name, *args) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/polyfill/v2_4/io/class/foreach.rb', line 7

def foreach(name, *args)
  hash, others = args.partition { |arg| arg.is_a?(::Hash) }

  chomps = hash[0] && hash[0][:chomp]

  unless block_given?
    if chomps
      separator = others.find { |other| other.respond_to?(:to_str) }

      return Enumerator.new do |yielder|
        block =
          if separator
            Proc.new do |line|
              yielder.yield(line.chomp(separator))
            end
          else
            Proc.new do |line|
              yielder.yield(line.chomp)
            end
          end
        super(name, *others, &block)
      end
    else
      return super(name, *others)
    end
  end

  block =
    if chomps
      separator = others.find { |other| other.respond_to?(:to_str) }
      if separator
        Proc.new do |line|
          yield(line.chomp(separator))
        end
      else
        Proc.new do |line|
          yield(line.chomp)
        end
      end
    else
      Proc.new
    end

  super(name, *others, &block)
end