Determine if a value is an instance of String , or Array , o


#1

each loop inside a mixed hash
I need to determine if the value is an instance of String
How ?

hash.each do |k,v|
if v ( instance of ) String
hash[ k ] = v.capitalize
enf
end


#2

On 3/4/06, oo00oo removed_email_address@domain.invalid wrote:

each loop inside a mixed hash
I need to determine if the value is an instance of String
How ?

hash.each do |k,v|
if v ( instance of ) String
hash[ k ] = v.capitalize
enf
end

Here’s two different ways of doing it … since I’m still pretty new to
ruby, I’m not sure if either of them is the best way (both use
capitalize!
rather to capitalize to change the value “in-place”):

hash.each do |k,v|
v.capitalize! rescue v
end

OR

hash.each do |k,v|
v.capitalize! if v.respond_to? :capitalize
end

Rick


#3

hash.each{|k,v|
v.capitalize! if v.is_a? String
}

Or use Rick’s “duck typing” approach.

oo00oo wrote:

each loop inside a mixed hash
I need to determine if the value is an instance of String
How ?

hash.each do |k,v|
if v ( instance of ) String
hash[ k ] = v.capitalize
enf
end


#4

Thanks for the tips
inline rescue is nice !
But I’m always searching a method to determine a type. For Arrays,
Hashs…


#5

object.is_a?(ClassName) does this.

object.class returns the class.

oo00oo wrote:

Thanks for the tips
inline rescue is nice !
But I’m always searching a method to determine a type. For Arrays,
Hashs…


#6

Also worth mentioning that you can do this:

hash.each do |k, v|
case v
when String
v.capitalize
when Array
# do something else
else
# do something else again
end
end

Pete Y.
http://9cays.com


#7

hash = {‘a’ => ‘bob’, ‘b’ => 3, ‘c’ => ‘fred’ }

hash.each_value {|d| d.capitalize! if d.is_a?(String) }
=> {“a”=>“Bob”, “b”=>3, “c”=>“Fred”}

So, to answer your question, use the is_a? (or kind_of?) method.

Bob S.
http://www.railtie.net/