Here's my example:
hash = {"buy"=>"Buy ", "quantity"=>"3 ", "get"=>"Get ", "reward"=>"1 ", "free"=>"Free"}
def stripit(value)
#value.gsub!('B', 'C')
value.gsub!('/\s+/', '')
value
end
newhash = hash.update(hash){|key,value| stripit(value)}
puts newhash.inspect
gsub
works on the value -- the first commented replacement works -- but for some reason it is not removing whitespace.
How can I remove whitespaces from a hash value?
You can use each
method with strip!
to modify hash values.
hash = {"buy"=>"Buy ", "quantity"=>"3 ", "get"=>"Get ", "reward"=>"1 ", "free"=>"Free"}
hash.each_value(&:strip!)
p hash
# => {"buy"=>"Buy", "quantity"=>"3", "get"=>"Get", "reward"=>"1", "free"=>"Free"}
I think the problem is that you've wrapped your regex in quotation marks, so it's not matching the way you expect!
value.gsub!(/\s+/, '')
(Edit: complete code, copies original question's code but alters the gsub! argument. Tested with ruby 2.3.1)
hash = {"buy"=>"Buy ", "quantity"=>"3 ", "get"=>"Get ", "reward"=>"1 ", "free"=>"Free"}
def stripit(value)
value.gsub!(/\s+/, '')
value
end
newhash = hash.update(hash){|key,value| stripit(value)}
puts newhash.inspect
Output:
{"buy"=>"Buy", "quantity"=>"3", "get"=>"Get", "reward"=>"1", "free"=>"Free"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With