What is an Enumerator object? (Created in String # gsub)

I have an array of attributes as follows:

attributes = ["test, 2011", "photo", "198.1 x 198.1 cm", "Photo: Manu PK Full Screen"] 

When i do this

 artist = attributes[-1].gsub("Photo:") p artist 

I get the following output in terminal

 #<Enumerator: "Photo: Manu PK Full Screen":gsub("Photo:")> 

I wonder why I get an enumerator object as output? Thanks in advance.

EDIT: Note that instead of attributes[-1].gsub("Photo:", ""), I am doing attributes[-1].gsub("Photo:") So I would like to know why the enumerator object came back here (I was expecting an error message) and what happens.?

Ruby - 1.9.2

Rails - 3.0.7

+6
source share
2 answers

The Enumerator object provides some common methods for enumerations - next , each , each_with_index , rewind , etc.

You get an Enumerator object here because gsub extremely flexible:

 gsub(pattern, replacement) → new_str gsub(pattern, hash) → new_str gsub(pattern) {|match| block } → new_str gsub(pattern) → enumerator 

In the first three cases, the replacement can be performed immediately and return a new line. But if you don't give a replacement string, a hash replacement, or a replacement block, you return an Enumerator object that allows you to jump to the matching fragments of the string to work later:

 irb(main):022:0> s="one two three four one" => "one two three four one" irb(main):023:0> enum = s.gsub("one") => #<Enumerable::Enumerator:0x7f39a4754ab0> irb(main):024:0> enum.each_with_index {|e, i| puts "#{i}: #{e}"} 0: one 1: one => " two three four " irb(main):025:0> 
+16
source

If no block or second argument is specified, gsub returns an enumerator. Check here for more information.

To remove it, you will need a second parameter.

 attributes[-1].gsub("Photo:", "") 

or

 attributes[-1].delete("Photo:") 

Hope this helps!

+5
source

Source: https://habr.com/ru/post/903656/


All Articles