2

How i can convert string into hash?

now i use:

eval "{'1627207:28320'=>'text'}"
=> {'1627207:28320'=>'text'}

but "eval" is not good for my case - string passed from params, and such case it is not secure

Edited:

passed string can also be:

"{'1627207'=>'text', '11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}"

Then need result hash:

{'1627207:28320'=>'text',
'11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}
Cœur
  • 37,241
  • 25
  • 195
  • 267
mpz
  • 1,906
  • 3
  • 15
  • 23

4 Answers4

4
str = "{'1627207:28320'=>'text'}"
p Hash[*str.delete("{}'").split('=>')] #{"1627207:28320"=>"text"}

edit for different input:

str = "{'1627207:28320'=>'text', 'key2'=>'text2'}" 
p Hash[*str.delete("{}'").split(/=>|, /)] #{"1627207:28320"=>"text", "key2"=>"text2"}
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • it is fine, but user can pass "{'1627207:28320'=>'text', 'key2'=>'text2'}" string. Then error: `ArgumentError: odd number of arguments for Hash from (irb):in `[]' – mpz May 03 '12 at 23:39
2
class String
  def to_h
    h={}
    self.scan(/'(\w+.\w+)'=>'(\w+)'/).each { |k,v| h[k]=v }
    h
  end
end

p "{'1627207:28320'=>'text','test'=>'text2'}".to_h
=>{"1627207:28320"=>"text", "test"=>"text2"}

EDIT: shorter version

class String
  def to_h
    Hash[self.scan(/'([^']+)'=>'([^']+)'/)]
  end
end
peter
  • 41,770
  • 5
  • 64
  • 108
  • worked for: `"{'key'=>'texttext' }"` but not worked for `"{'key'=>'text text' }"` – mpz May 03 '12 at 23:55
  • well, the regex needs to be oriented towards the kind of inpout that needs to be processed, adapted the shorter version to look for the char ' as delimiter – peter May 04 '12 at 07:23
0

Quite straight forward:

$ irb
irb(main):001:0> k='1627207:28320'
=> "1627207:28320"
irb(main):002:0> v='text'
=> "text"
irb(main):003:0> h={k => v}
=> {"1627207:28320"=>"text"}
irb(main):004:0> h
=> {"1627207:28320"=>"text"}
irb(main):005:0>
Miquel
  • 4,741
  • 3
  • 20
  • 19
  • But you don't parse string, just creating a hash from variables – Grzegorz Łuszczek May 02 '12 at 08:56
  • What kind of parsing he does? In his example he gets from text to hash. If he gets an string looking like a hash then parsing is necessary as Grzegorz pointed out – Miquel May 02 '12 at 08:58
  • He gets `"{'some_key' => 'value'}"` string, but also could get `"{'first' => 1, 'second' => 2}"`, becouse both strings contains hash. So he need a code that could convert all string to hash – Grzegorz Łuszczek May 02 '12 at 09:02
  • In that case parsing is needed, maybe he could use JSON.decode() – Miquel May 02 '12 at 09:05
  • Parsing is necessary to interpolate the string content. Even you use eval, JSON or other libraries, they do the same thing. – SwiftMango May 02 '12 at 13:54
0

You could simply try this:

text_hash['1627207:28320'] = 'text'
text_hash
wchargin
  • 15,589
  • 12
  • 71
  • 110
legendary_rob
  • 12,792
  • 11
  • 56
  • 102