Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove whitespace from a string in a hash

Tags:

ruby

hash

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?

like image 330
user3063045 Avatar asked Dec 09 '16 15:12

user3063045


2 Answers

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"}
like image 72
Lukas Baliak Avatar answered Sep 28 '22 19:09

Lukas Baliak


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"}
like image 27
jdussault Avatar answered Sep 28 '22 18:09

jdussault