Project

General

Profile

Feature #3767

String#scan enumerator?

Added by trans (Thomas Sawyer) about 9 years ago. Updated over 8 years ago.

Status:
Rejected
Priority:
Normal
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

History

#1

Updated by runpaint (Run Paint Run Run) about 9 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

#2

Updated by naruse (Yui NARUSE) about 9 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

#3

Updated by trans (Thomas Sawyer) almost 9 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

#4

Updated by naruse (Yui NARUSE) almost 9 years ago

  • Status changed from Feedback to Rejected

=begin
No feedback.
=end

Also available in: Atom PDF