Forum: Ruby-core [Ruby 1.9-Feature#3767][Open] String#scan enumerator?

Posted by Thomas Sawyer (Guest)
on 2010-08-30 19:59
(Received via mailing list)
Feature #3767: String#scan enumerator?
http://redmine.ruby-lang.org/issues/show/3767

Author: Thomas Sawyer
Status: Open, Priority: Normal
Category: lib

Should String#scan return an Enumerator if no block is given?

I came across this issue when testing a String extension I have that 
works in 1.8, but not 1.9 b/c String is no longer enumerable.

  class String

    # Returns an Enumerator for iterating over each
    # line of the string, stripped of whitespace on
    # either side.
    #
    def cleanlines(&block)
      if block
        scan(/^.*?$/) do |line|
          block.call(line.strip)
        end
      else
        Enumerator.new(self) do |output|
          scan(/^.*?$/) do |line|
            output.yield(line.strip)
          end
        end
      end
    end

  end
Posted by Run Paint Run Run (Guest)
on 2010-10-28 20:41
(Received via mailing list)
Issue #3767 has been updated by Run Paint Run Run.


> Should String#scan return an Enumerator if no block is given?

Perhaps, but it can't because that would be incompatible with previous 
1.9 releases. For instance, `s.scan(/./)[0]` would no longer work as 
Enumerators don't define #[]. So, -1 from me.
Posted by Yui NARUSE (Guest)
on 2010-10-29 02:41
(Received via mailing list)
Issue #3767 has been updated by Yui NARUSE.

Status changed from Open to Feedback

Why don't you use Object#to_enum and String#each_line?

> str = "a\nb\nc"
=>"a\nb\nc"
> enum = str.to_enum(:each_line)
=> #<Enumerable::Enumerator:0x7f62e51c7600>
irb(main):014:0> e.each{|l|p l}
"a\n"
"b\n"
"c"
=>"a\nb\nc"
Posted by Thomas Sawyer (Guest)
on 2010-12-13 21:56
(Received via mailing list)
Issue #3767 has been updated by Thomas Sawyer.


@Yui
Yes, :each_line could be used for this particular this example b/c of 
the regular expression used, but not in the general case.

@Run Paint Run Run
That's a good point. So, it would be a bigger deal than I expected. But 
I wonder if #[] could be defined for Enumerator? Wouldn't it mean 
applying the enumeration method and breaking out after n iterations with 
the current value of the loop? That might actually be useful in other 
cases.
Posted by Yui NARUSE (Guest)
on 2010-12-26 06:56
(Received via mailing list)
Issue #3767 has been updated by Yui NARUSE.

Status changed from Feedback to Rejected

No feedback.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.