Ruby/Rhomobile: parse directory string representation - ruby

I have a string that looks like this: {"whatever-field"=>"gghyduudud"}
I'd like to parse it so that it becomes a hash.
Please help.
Thanks!

You can use eval, but only if the data source is absolutely reliable:
>> eval('{"whatever-field"=>"gghyduudud"}')
=> {"whatever-field"=>"gghyduudud"}

Here is a solution:
dictionary=Hash[*(dict_str[1..dict_str.length-2].split("=>").map {|strval| strval[1..strval.length-2]})]
That will work as long as you want the keys and values as strings. Its a bit long, but it worked for me.

Related

How do I best dump a Psych::Nodes::Document back to a YAML string?

This does what I want, but going via to_ruby seems unnecessary:
doc = Psych.parse("foo: 123")
doc.to_ruby.to_yaml
# => "---\nfoo: 123\n"
When I try to do this, I get an error:
DEV 16:49:08 >> Psych.parse("foo: 123").to_yaml
RuntimeError: expected STREAM-START
from /opt/…/lib/ruby/2.5.0/psych/visitors/emitter.rb:42:in `start_mapping'
I get the impression that the input needs to be a stream of some sort, but I don't quite get what incantation I need. Any ideas?
(The problem I'm trying to solve here, by the way (in case you know of a better way) is to fix some YAML that can't be deserialised into Ruby, because it references classes that don't exist. The YAML is quite complex, so I don't want to just search-and-replace in the YAML string. My thinking was that I could use Psych.parse to get a syntax tree, modify that tree, then dump it back into a YAML string.)
Figured out the incantation after finding the higher-level docs at https://ruby-doc.org//stdlib-2.3.0_preview1/libdoc/psych/rdoc/Psych/Nodes.html, though please let me know if there's a better way:
doc = Psych.parse("foo: 123")
stream = Psych::Nodes::Stream.new
stream.children << doc
stream.to_yaml
# => "foo: 123\n"

Ruby string to int/float conversion

So let's say I have a string, '$3,444.11'. How do I convert that to a float 3,444.11? I have a form field. The user can insert "3,444.11", "3444.11", or "$3,444.11" or "€3,444.11". What I need is 3,444.11 as a float. Will I have to resort to regex? Or, is there a function already that I'm overlooking?
I don't think there's anything in the standard library that does this for you. Here's a quick one-liner:
'$3,444.11'.gsub(/[^\d\.]/, '').to_f
# => 3444.11
However, you might want to take a look at the money gem for advanced processing of currency strings.

Regex array (["number", "number",...])

Can you help me with expression for array: ["232","2323","233"]
I try this: /^\[("\d{1,7}")|(,"\d{1,7}")\]$/
But this expression is not working properly.
I use ruby(rails).
This would validate the array structure well, blocking an entry like [,"123"]
^\[(("\d{1,7}")(,"\d{1,7}")*)?\]$
You may try this ( though it may allow leading ,):
^\[(,?"\d{1,7}")*]$
Try this: /^\[("\d{1,7}")(, ?"\d{1,7}")*\]$/

Convert string with comma to integer

Is there any neat method to convert "1,112" to integer 1112, instead of 1?
I've got one, but not neat:
"1,112".split(',').join.to_i #=> 1112
How about this?
"1,112".delete(',').to_i
You may also want to make sure that your code localizes correctly, or make sure the users are used to the "international" notation. For example, "1,112" actually means different numbers across different countries. In Germany it means the number a little over one, instead of one thousand and something.
Corresponding Wikipedia article is at http://en.wikipedia.org/wiki/Decimal_mark. It seems to be poorly written at this time though. For example as a Chinese I'm not sure where does these description about thousand separator in China come from.
Some more convenient
"1,1200.00".gsub(/[^0-9]/,'')
it makes "1 200 200" work properly aswell
The following is another method that will work, although as with some of the other methods it will strip decimal places.
a = 1,112
b = a.scan(/\d+/).join().to_i => 1112
I would do using String#tr :
"1,112".tr(',','').to_i # => 1112
If someone is looking to sub out more than a comma I'm a fan of:
"1,200".chars.grep(/\d/).join.to_i
dunno about performance but, it is more flexible than a gsub, ie:
"1-200".chars.grep(/\d/).join.to_i
String count = count.replace(",", "");

Parsing URL string in Ruby

I have a pretty simple string I want to parse in ruby and trying to find the most elegant solution. The string is of format
/xyz/mov/exdaf/daeed.mov?arg1=blabla&arg2=3bla3bla
What I would like to have is :
string1: /xyz/mov/exdaf/daeed.mov
string2: arg1=blabla&arg2=3bla3bla
so basically tokenise on ?
but can't find a good example.
Any help would be appreciated.
I think the best solution would be to use the URI module. (You can do things like URI.parse('your_uri_string').query to get the part to the right of the ?.) See http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/
Example:
002:0> require 'uri' # or even 'net/http'
true
003:0> URI
URI
004:0> URI.parse('/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf')
#<URI::Generic:0xb7c0a190 URL:/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf>
005:0> URI.parse('/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf').query
"arg1=bla&arg2=asdf"
006:0> URI.parse('/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf').path
"/xyz/mov/exdaf/daeed.mov"
Otherwise, you can capture on a regex: /^(.*?)\?(.*?)$/. Then $1 and $2 are what you want. (URI makes more sense in this case though.)
Split the initial string on question marks.
str.split("?")
=> ["/xyz/mov/exdaf/daeed.mov", "arg1=blabla&arg2=3bla3bla"]
This seems to be what youre looking for, strings built-in split function:
"abc?def".split("?") => ["abc", "def"]
Edit: Bah, to slow ;)

Resources