Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Is there something like Enumerable#drop that returns an enumerator instead of an array?

I have some big fixed-width files and I need to drop the header line.

Keeping track of an iterator doesn't seem very idiomatic.

# This is what I do now.
File.open(filename).each_line.with_index do |line, idx|
  if idx > 0
     ...
  end
end

# This is what I want to do but I don't need drop(1) to slurp
# the file into an array.
File.open(filename).drop(1).each_line do { |line| ... }

What's the Ruby idiom for this?

like image 957
Samuel Danielson Avatar asked Feb 04 '10 13:02

Samuel Danielson


People also ask

Is Hash enumerable Ruby?

Some Ruby classes include Enumerable: Array. Dir. Hash.

What is .all in Ruby?

The all?() of enumerable is an inbuilt method in Ruby returns a boolean value true if all the objects in the enumerable satisfies the given condition, else it returns false. If a pattern is given, it compares with the pattern, and returns true if all of them are equal to the given pattern, else it returns false.

What is an enumerable method?

Enumerable methods work by giving them a block. In that block you tell them what you want to do with every element. For example: [1,2,3].map { |n| n * 2 } Gives you a new array where every number has been doubled.

What does .find do in Ruby?

The find method locates and returns the first element in the array that matches a condition you specify. find executes the block you provide for each element in the array. If the last expression in the block evaluates to true , the find method returns the value and stops iterating.


2 Answers

This is slightly neater:

File.open(fname).each_line.with_index do |line, lineno|
  next if lineno == 0
  # ...
end

or

io = File.open(fname)
# discard the first line
io.gets
# process the rest of the file
io.each_line {|line| ...}
io.close
like image 78
glenn jackman Avatar answered Sep 27 '22 19:09

glenn jackman


If you need it more than once, you could write an extension to Enumerator.

class Enumerator
  def enum_drop(n)
    with_index do |val, idx|
      next if n == idx
      yield val
    end
  end
end

File.open(testfile).each_line.enum_drop(1) do |line|
  print line
end

# prints lines #1, #3, #4, …
like image 42
Debilski Avatar answered Sep 27 '22 21:09

Debilski