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?
Some Ruby classes include Enumerable: Array. Dir. Hash.
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.
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.
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.
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
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, …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With