What is Enumerator object? (Created with String#gsub)
Asked Answered
A

2

12

I have an attributes array 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:")>

Wondering why am I getting an enumerator object as output? Thanks in advance.

EDIT: Please note that instead of attributes[-1].gsub("Photo:", ""), I am doing attributes[-1].gsub("Photo:") So would like to know why enumerator object has returned here( I was expecting an error message) and what is going on.?

Ruby - 1.9.2

Rails - 3.0.7

Asceticism answered 13/12, 2011 at 6:52 Comment(0)
O
19

An Enumerator object provides some methods common to enumerations -- next, each, each_with_index, rewind, etc.

You're getting the Enumerator object here because gsub is 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 substitution can take place immediately, and return a new string. But, if you don't give a replacement string, a replacement hash, or a block for replacements, you get back the Enumerator object that lets you get to the matched pieces of the string to work with 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> 
Oppression answered 13/12, 2011 at 7:2 Comment(0)
T
5

When neither a block nor a second argument is supplied, gsub returns an enumerator. Look here for more info.

To remove it, you need a second parameter.

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

Or

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

Hope this helps!!

Tolyl answered 13/12, 2011 at 7:2 Comment(1)
Note with #delete it will delete every character in the given string, not the word. e.g. "Photo of an otter".delete("Photo:") # => " f a er"Hinterland

© 2022 - 2024 — McMap. All rights reserved.