Reputation: 55
Currently attempting to adjust all the string values of a hash to lowercase. This hash contains multiple value types (nil, string, integer) so running across the entire hash with downcase spits out an error due to the nil values in the hash.
NoMethodError: undefined method "downcase!" for nil:NilClass
I'm pretty brand new to Ruby and I wasn't sure how best to run through this hash and skip the nil or integer values. I've attempted to use .map to convert every value to string and then downcase the values, but I'm either not seeing any difference in the end result or I get an error.
testHash = testHash.map(&:to_s)
testHash.map(&:downcase!)
(I've also attempted testHash.each {|k,v| v.downcase!}
I'm sure most of this is me just not knowing how to write this out in Ruby correctly. Please let me know if you need additional info and thank you.
Upvotes: 0
Views: 2759
Reputation: 10432
h = {a: nil, b: "Someword", c: 1}
h.map {|k,v| v.downcase! if v.is_a? String}
puts h #=> {:a=>nil, :b=>"someword", :c=>1}
This will work. I am mapping through the hash and check for values that are strings, and then running the downcase!
method.
Upvotes: 1
Reputation: 1342
Check if the value is a valid string before downcasing
testHash.each { |k, v| v.downcase! if v.is_a?(String) }
Upvotes: 3