Need help on #grep

I was trying to list the all the class names having the pattern `stri`
with the below:

p ObjectSpace.each_object(Class).to_a.grep(/(stri)/i) #=> []

But not getting the output. So can anyone help me on the same?

Thanks

Love U Ruby wrote in post #1108785:

I was trying to list the all the class names having the pattern `stri`
with the below:

p ObjectSpace.each_object(Class).to_a.grep(/(stri)/i) #=> []

But not getting the output. So can anyone help me on the same?

ObjectSpace.each_object(Class) is returning an Enumerator of Class
object. Then you are shoving a bunch of class objects into an array and
then expecting grep to know what to do with them.

If you were to run:

irb(main):> ObjectSpace.each_object(Class) { |x| p x.class }
Class
Class
Class
...
...
...
=> 383

Calling to_a on that Enumerator you get an array of Class objects, NOT
strings. When sending the grep message to an Array return any elements
where Pattern === element.

What you probably want instead is an array of class names as strings not
Class objects. Then grep should work just fine.

I got only one:

ObjectSpace.each_object(Class).map(&:name).grep(/stri/i)
#=> ["String"]

How to get all using regex,which has a substring `stri`?

Try:

ObjectSpace.each_object(Class).to_a.map(&:to_s).grep(/(stri)/i)

Sorry, no need of "to_a" :slight_smile:

Javier Quarite wrote in post #1108835:

Try:

ObjectSpace.each_object(Class).to_a.map(&:to_s).grep(/(stri)/i)

#=> ["String"]

well, there’s might be some differences in our setups (or something else)

I got this :

[“RubyToken::TkDXSTRING”, “RubyToken::TkDSTRING”, “RubyToken::TkXSTRING”, “RubyToken::TkSTRING”, “String”]

ObjectSpace.each_object(Class).select { |x| x.to_s =~ /stri/i }

=> [String, RubyToken::TkDXSTRING, RubyToken::TkDSTRING, RubyToken::TkXSTRING, RubyToken::TkSTRING]

(Hello from Ruby 2.0)

Other solutions give you the stringified class name. The above gives you the class object, in case you want to do something with it beside fettle its characters.

Nitpick: the () aren’t necessary in that regex; they’re only needed if you’re capturing part of the output. E.g.,

ObjectSpace.each_object(Class).map { |x| x.to_s =~ /(.*)::.*stri/i and $1 }.compact.uniq

=> [“RubyToken”]

ObjectSpace.each_object(Class).to_a.map(&:to_s).grep(/(.*)::.*stri/i) { |_| $1 }.uniq

=> [“RubyToken”]

Paul

Javier Quarite wrote in post #1108844:

well, there's might be some differences in our setups (or something
else)

I got this :

["RubyToken::TkDXSTRING", "RubyToken::TkDSTRING",
"RubyToken::TkXSTRING",
"RubyToken::TkSTRING", "String"]

Yes when I ran it from SublimeText2 getting only ["String"]. But when I
ran it from `IRB`,getting the result as you got.

my Ruby version is:

C:\>ruby -v
ruby 1.9.3p374 (2013-01-15) [i386-mingw32]