Project

General

Profile

Actions

Feature #3767

closed

String#scan enumerator?

Added by trans (Thomas Sawyer) over 13 years ago. Updated almost 13 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:31954]

Description

=begin
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
=end

Actions #1

Updated by runpaint (Run Paint Run Run) over 13 years ago

=begin

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.
=end

Actions #2

Updated by naruse (Yui NARUSE) over 13 years ago

  • Status changed from Open to Feedback

=begin
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"
=end

Actions #3

Updated by trans (Thomas Sawyer) over 13 years ago

=begin
@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.

=end

Actions #4

Updated by naruse (Yui NARUSE) over 13 years ago

  • Status changed from Feedback to Rejected

=begin
No feedback.
=end

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0