How do you use variables in regex? - ruby-on-rails

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

Related

Remove characters after any tags

I am working in rails. I have one doubt.
1. a = "ABCD123"
I want to print ABCD123
2. b = "ABCDE<123>"
I want to print ABCDE
For that I am using this
a.scan(/\b[A-Za-z]+\b/).join and
b.scan(/\b[A-Za-z]+\b/).join.
First one is giving nil but I want to print it as ABCD123 and second one is showing correct what I want.
Could anyone please help me. Thanks.
code below can remove all tags in the string
a = "ABCD123"
b = "ABCDE<123>"
a.gsub /<.*?>/, '' # => "ABCD123"
b.gsub /<.*?>/, '' # => "ABCDE"
def conversion(str)
index_number = str.index(/[\W_]+/)
if index_number.present?
main_str = str.gsub(str[index_number..],'')
else
main_str = str
end
return main_str
end
or you can use
b = "ABCD-123"
b.match(/(^[A-Za-z0-9]+)/)[1]
#=> "ABCD"
You can try following,
b = "ABCDE<123>"
b[/[^<>]+/]
# => "ABCDE"
Since comments are a bit limited:
Here is a small snippet to test different inputs.
strings = %w[ABCD123 ABCD<123> ABCD <123>ABCDE]
strings.each do |string|
match = string.match(/(^[A-Za-z0-9]+)/)
if match
puts "'#{string}' => #{match[1]}"
else
puts "'#{string}' does not match pattern"
end
end
Is this the desired behaviour?
'ABCD123' => ABCD123
'ABCD<123>' => ABCD
'ABCD' => ABCD
'<123>ABCDE' does not match pattern

New DateTime instead of String in ruby

I've got some issue with DateTime in Ruby
I've got line which looks like this (it's in .txt file)
DateTime.new(1979,1,1) DateTime.new(2012,3,29)
And my function to get this looks like this
def split_line
array = line.split(' ')
#date_of_birth = array[0]
#date_of_death = array[1]
end
But #date_of_birth and #date_of_death class are String. How can I get them as DateTime?
Assuming your string is in the correct format, then you're probably looking for:
#date_of_birth = array[0].to_datetime
#date_of_death = array[1].to_datetime
See here for more info:
https://apidock.com/rails/String/to_datetime
This:
DateTime.new(1979,1,1) DateTime.new(2012,3,29)
Is not code. What do you expect that to do?
If you want two DateTimes as a space-separated string, do something like:
"#{DateTime.new(1979,1,1)} #{DateTime.new(2012,3,29)}"
When you have something like #{...} inside a set of double quotation marks (they must be double, not single quotation marks), it's called string interpolation. Learn it. Love it. Live it.
But, for the life of me, I don't know why you wouldn't do:
[DateTime.new(1979,1,1), DateTime.new(2012,3,29)]
Which gives you an array, so no split needed. Just:
def split_line
#date_of_birth = array[0]
#date_of_death = array[1]
end
If you want DateTime values, grab the numbers and create them:
require 'date'
'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split.map { |s|
DateTime.new(*s.scan(/\d+/).map(&:to_i) )
}
# => [#<DateTime: 1979-01-01T00:00:00+00:00 ((2443875j,0s,0n),+0s,2299161j)>,
# #<DateTime: 2012-03-29T00:00:00+00:00 ((2456016j,0s,0n),+0s,2299161j)>]
The values aren't DateTime though, they're Dates:
'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split.map { |s|
Date.new(*s.scan(/\d+/).map(&:to_i) )
}
# => [#<Date: 1979-01-01 ((2443875j,0s,0n),+0s,2299161j)>,
# #<Date: 2012-03-29 ((2456016j,0s,0n),+0s,2299161j)>]
Breaking it down:
'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split # => ["DateTime.new(1979,1,1)", "DateTime.new(2012,3,29)"]
.map { |s|
Date.new(
*s.scan(/\d+/) # => ["1979", "1", "1"], ["2012", "3", "29"]
.map(&:to_i) # => [1979, 1, 1], [2012, 3, 29]
)
}
# => [#<Date: 1979-01-01 ((2443875j,0s,0n),+0s,2299161j)>,
# #<Date: 2012-03-29 ((2456016j,0s,0n),+0s,2299161j)>]
* (AKA "splat"), used like this, explodes an array into its elements, which is useful when you have an array but the method only takes separate parameters.
The bigger question is why you're getting values like that in a text file.

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 to get key/value from xpath string

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.

ruby string escape when adding

In Ruby on Rails,I got a string number is made of 3 parts : prefix , counter , suffix
In model Setup:
def self.number
prefix = setup.receipt_prefix.blank? ? "" : setup.receipt_prefix.to_s
counter = setup.receipt_counter.blank? ? "" : setup.receipt_counter+1
suffix = setup.receipt_suffix.blank? ? "" : setup.receipt_suffix.to_s
each individual string shows fine:
puts prefix
=> \#_
puts counter
=>
1234
puts suffix
=>
#$#s
but when I add 3 string together, an addition back slash appear :
prefix + counter + suffix
=>
\\#_1234\#$#s
how can I escape "#" "\" when I add 3 string together ? like
=>
\#_1234#$#s
any Ruby or Rails's helper I can use in the model?
thx~~
The string will look different if you get the value versus print (puts) it out. See the following irb session.
>> a = "\\#_"
=> "\\#_"
>> puts a
\#_
=> nil
>> b = "1234"
=> "1234"
>> puts a + b
\#_1234
=> nil
>> a + b
=> "\\#_1234"
The actual string value has two backslashes in it. But only one shows up if you print the string.

Resources