If you are trying to limit the number of characters IO#each_line
can help you with this e.g.
c_max = 100
File.open(filename) do |file|
file.each_line(c_max) do |characters|
# characters is now a string that is 100 characters long
# do something with characters
end
end
Or to handle a String
you can make it a StringIO
and #each_line
will work too (Please note String#each_line
will not work as it only accepts a separator (String
) and not a character limit (Fixnum
) this is why we need StringIO
)
s = "THIS IS A STRING"
StringIO.open(s) do |strio|
strio.each_line(2) do |characters|
# characters is now a string that is 2 characters long
# do something with characters
end
end
So let's handle both options Update: (Based on comment discussion with @CarySwoveland - Thanks for pushing me further)
def do_stuff(line)
# common functionality goes here
puts line
end
# return is a StringIO or File
# leaks file descriptor handle as you wish
def my_method(s,sep_or_char_limit=100)
target = s.to_s # leverage a little duck typing
target_class = File.file?(target) ? File : StringIO
target_class.open(target) do |io|
io.each_line(sep_or_char_limit, &method(:do_stuff))
end
end
Since this uses Enumerator functionality it will also help with memory consumption since the whole File
need not be read into memory first or the whole String
does not need to be split into a temporary Array
.
There is additional hidden functionality here as well. You asked for limitation by characters but this will also allow for a separator if you prefer. e.g.
# Using a Character Limit
my_method("THIS IS A STRING",2)
# TH
# IS
# I
# S
# A
# ST
# RI
# NG
# Using a separator
my_method("THIS IS A STRING",' ')
# THIS
# IS
# A
# STRING