Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 631
nkm Avatar asked Dec 13 '11 06:12

nkm


People also ask

What is an enumerator object Ruby?

Enumerator, specifically, is a class in Ruby that allows both types of iterations – external and internal. Internal iteration refers to the form of iteration which is controlled by the class in question, while external iteration means that the environment or the client controls the way iteration is performed.

How do I use GSUB in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.


1 Answers

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> 
like image 66
sarnold Avatar answered Nov 03 '22 00:11

sarnold