From: Robert Klemme Date: 2009-08-24T23:44:23+09:00 Subject: Re: 1.8.7 String#lines keeps new-line chars (say it ain't so in 1.9) 2009/8/24 Trans : > > > On Aug 24, 9:17 am, Brian Candler wrote: >> Thomas Sawyer wrote: >> > To me returning the newline code with #lines would be like returning >> > the spaces for a method #words. Eg. >> >> >   "show it\nto me".words => ["show ", "it\n", "to ", "me "] >> >> ...except there is no built-in method 'words' so you can't accuse it of >> being inconsistent :-) > > ok ;) ...just making an analogy. > >> Some people would want lines with trailing whitespace stripped as well >> as terminators. Some people would want leading whitespace stripped too. >> I don't think you can please everyone, so IMO the most flexible and >> consistent approach is to give the line complete with its terminator, >> and let the user apply whatever post-processing they like. > > Sure, but at that point we are moving into a realm of narrower > usecases. I believe the short, more concise method name should go to > the most frequent use. I have no definitive statistics, but I'd wager > that split("\n") is by far the more common case. Based on that, I'd > rather see the current def be called something else, like #newlines or > #rawlines. But Ruby is ultimately Matz' baby so maybe his more common > use is otherwise. I don't think it is a good idea to change the default behavior. If you frequently need line endings stripped, you can always define your own method for this, for example: class LineEnum include Enumerable def initialize(obj, meth = case obj when String, IO then :each_line else :each end) @obj = obj @meth = meth end def each @obj.send(@meth) do |elem| elem.chomp! yield elem end self end end $ irb19 -r lineenum.rb Ruby version 1.9.1 irb(main):001:0> s = "foo\nbar\n" => "foo\nbar\n" irb(main):002:0> se = LineEnum.new s => # irb(main):003:0> se.each {|l| p l} "foo" "bar" => # irb(main):004:0> We could also extend Enumerator to honor blocks passed to them so we could do $stdin.to_enum(:each_line) {|l| l.strip!}.each do |line| p line # no \n present end But frankly, I'd rather just add a "line.chomp!" to my block body and be done. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/