how to get key/value from xpath string - ruby-on-rails

I'm working on ruby on rails project and I have a string
cmd = "\"//div/table/tbody/tr/td/label[text()=\"Select Year\"]/preceding-sibling::*[1]\" = \"2014\""
I want to get key/value like this:
key: "//div/table/tbody/tr/td/label[text()=\"Select Year\"]/preceding-sibling::*[1]"
value: "2014"
The key is a xpath. I was using cmd.split("=") which is not correct. I think i can use regex to parse the string but don't know how. Please advice.
Thank you in advance!

using split will work for you .
2.1.1 :006 > cmd = '"//div/table/tbody/tr/td/label[text()=\"Select Year\"]/preceding-sibling::*[1]" = "2014"'
=> "\"//div/table/tbody/tr/td/label[text()=\\\"Select Year\\\"]/preceding-sibling::*[1]\" = \"2014\""
2.1.1 :007 > cmd.split(" = ")[0]
=> "\"//div/table/tbody/tr/td/label[text()=\\\"Select Year\\\"]/preceding-sibling::*[1]\""
2.1.1 :008 > cmd.split(" = ")[1]
=> "\"2014\""
save the first as key and the second as value.

Now, i got solution. See below:
my original string:
a = "\"//div/table/tbody/tr/td/label[text()=\\\"Select Year\\\"]/preceding-sibling::*[1]\" = \"2014\""
I'm using:
a.match('[\w\W]*\"[\s]*=')[0]
to get string:
"\"//div/table/tbody/tr/td/label[text()=\\\"Select Year\\\"]/preceding-sibling::*[1]\" ="
Then i can use substring to get the rest string.

Related

how to convert the given string to array in rails

I have the following Strings. I want them to convert into Arrays like below in rails
"[\"Winter\", \"Summer\", \"Spring\"]" to ["Winter", "Summer", "Spring"]
"[\"IELTS\", \"GRE\", \"PTE\", \"SAT\"]" to ["IELTS", "GRE", "PTE", "SAT"]
How can i convert these
You can do it with JSON.
require 'json'
string = "[\"Winter\", \"Summer\", \"Spring\"]"
JSON.parse(string)
=> ["Winter", "Summer", "Spring"]
just alternate solution (not safe) :
> string = "[\"Winter\", \"Summer\", \"Spring\"]"
> eval(string)
#=> ["Winter", "Summer", "Spring"]
Note: better option to parse with JSON

Change default decimal numbers parsing behavior

I am getting the following response of a web service call:
response = "{\"price\":39.74000000000000198951966012828052043914794921875}"
Then I'm parsing it:
json = JSON.parse(response, {:symboize_names: true})
The result is:
json = {price: 39.74}
Then I tried from Rails console to check if it is happening because of JSON library, but simply I got the following result:
>> data = {:price => 39.74000000000000198951966012828052043914794921875}
{:price=>39.74}
So it's default behavior in Rails and I need to change it (on application level) to always parse decimal numbers as BigDecimal instead of float.
Ruby = 2.3.0
Rails = 4.2.4
Can anybody help?
The solution is a hack really, but I couldn't find any better
response = "{\"price\":39.74000000000000198951966012828052043914794921875}"
transformed_response = response.gsub(/\d+\.\d+/, '"\&"')
hash = JSON.parse(transformed_response , symboize_names: true})
The resulting hash will be
{ price: "39.74000000000000198951966012828052043914794921875" }
With which you can do something like this
hash.tap { |hash| hash[:price] = BigDecimal.new(hash[:price]) }

Rails - good way to convert string to array if not array rails

I receive a param and want it to be either a string like this :
"abc,efg"
or an Array like this
["abc","efg"]
In the first case I want to convert it into an Array, what would be the good way ?
Here is what I thought
if params[:ids] && params[:ids].is_a? Array
ids = params[:ids]
else if params[:ids]
ids = params[:ids].split(",")
I'd use a ternary for this to keep it simple and on one line:
ids = params[:ids].is_a?(String) ? params[:ids].split(',') : params[:ids]
I've reversed the order so you don't get an undefined method error if you try calling split on nil should params[:ids] be missing.
Array.wrap(params[:ids]).map{|x| x.split(',')}.flatten
Apologies for piling on. But I thought I would offer a slight tweak to the answer proposed by SickLickWill (which doesn't quite handle the Array case correctly):
ids = params[:id].split(',').flatten
This will handle the String case just fine:
:001 > params = {id: "abc,efg"}
:002 > ids = params[:id].split(',').flatten
=> ["abc", "efg"]
As well as the Array case:
:003 > params = {id: ["abc","efg"]}
:004 > ids = params[:id].split(',').flatten
=> ["abc", "efg"]
If there's any chance the id param will be nil, then this barfs:
:005 > params = {}
=> {}
:006 > ids = params[:id].split(',').flatten
NoMethodError: undefined method `split' for nil:NilClass
So, you could put in a conditional test:
:007 > ids = params[:id].split(',').flatten if params[:id]
=> nil
Or, use try:
:008 > ids = params[:id].try(:split, ',').try(:flatten)
=> nil
You miss end tag and you have wrong else if and you can delete the check of params[:ids] because if :ids key do not exist is_a? return NilClass
I think you can do this
ids = if params[:ids].is_a? Array
params[:ids]
elsif params[:ids]
params[:ids].split(",")
end
I think the shortest way would be to use .try. It saves you from writing out an if-then-else.
params_id = params[:id].try(:split, ',')

Removing leading and trailing double quotes in string in rails

I want to trim the leading and trailing quotes of a string without any replacement.. I have tried with gsub.. but nothing helped.. I want to achieve something like., "hai" to hai
In Java, I ll use like the following.,
String a="\"hai";
String z=a.replace("\"", "");
System.out.println(z);
Output:
hai
How can I achieve this in rails? Kindly pls help..
In my irb
2.2.3 :008 > str = "\"hai"
=> "\"hai"
2.2.3 :009 > str.tr!('\"', '')
=> "hai"
Why am I not able to get output without double quotes?? Sorry ., If my question doesn't meet your standard..
You can also use .tr method.
str = "\"hai"
str = str.tr('\"', '')
##OR
str.tr!('\"', '')
## OUTPUT
"hai"
You can pass a regex instead, try this
str = "\"hai"
str = str.gsub(/\"/, '')
Hope that helps!
This removes the leading and trailing double quotes from the string only. You get a new string and keep the old one.
str = "\"ha\"i\""
# => "\"ha\"i\""
new_str = str.gsub(/^"+|"+$/, '')
# => "ha\"i"
str
# => "\"ha\"i\""
Or you change the original string.
str.gsub!(/^"+|"+$/, '')
# => "ha\"i"
str
# => "ha\"i"
That's a ruby convention. Method names with an exclamation mark/point modify the object itself.
This should work:
str = "\"hai"
str.tr('"', '')
Note that you only escape (\") double-quotes in a string that is defined using double-quotes ("\""), otherwise, you don't ('"').

How do you use variables in regex?

I am trying to pull from this string the photo ID : 30280 :
"--- !ruby/struct:PhotoJob \nimage_id: 30280\n"
I've seen this sort of thing done in regex before where you can look for a couple parameters that match like /nimage_id: \d/ and then return \d.
How can I return /d or the number 30280 from that string?
What's funny is that you have a Ruby Struct there, so you could do the following and let YAML take care of the parsing.
PhotoJob = Struct.new(:image_id)
job = YAML.load("--- !ruby/struct:PhotoJob \nimage_id: 30280\n")
job.image_id
=> 30280
use group matches "--- !ruby/struct:PhotoJob \nimage_id: 30280\n".scan(/image_id: (\d+)/)[0]
>> matches = "--- !ruby/struct:PhotoJob \nimage_id: 30280\n".match(/struct:(.*) .*image_id: (\d+)/m)
=> #<MatchData "struct:PhotoJob \nimage_id: 30280" 1:"PhotoJob" 2:"30280">
>> matches[1]
=> "PhotoJob"
>> matches[2]
=> "30280"
str = "--- !ruby/struct:PhotoJob \nimage_id: 30280\n"
image_id = str.scan(/\d+/)[0]
#=> "30280"
RE = '\nimage_id: (\d+)\n'
The group defined by parentheses around \d+ catches the number

Resources