How to find and remove the string from string using ruby? - ruby

I want to find & remove a string from string. See the examples below,
Input1:
a = 'mangalore'
Input2
b = 'mc'
Outputs
b values should not present in a for output1 #angalore
a values should not present in b for output2 #c
Solutions: converting string a,b to array then doing a-b & b-a
it will give results. How to implement using string in ruby.
Helps appreciated!

Use String#tr:
main > 'mangalore'.tr 'mc', '#'
#⇒ "#angalore"
main > 'mc'.tr 'mangalore', '#'
#⇒ "#c"

Related

The letter disapperaed after Splitting string in my ruby program

I am newbie in ruby. In my ruby program, there is a part of code for parsing geocode. The code is like below:
string = "GPS:3;S23.164865;E113.428970;88"
info = string.tr("GPS:",'')
info_array = info.split(";")
puts "GPS: #{info_array[0]},#{info_array[1]},#{info_array[2]}"
The code should split the string into 3 piece: 3, S23.164865 and E113.428970;88 and the expected output is
GPS: 3,S23.164865,E113.428970
but the result is:
GPS: 3,23.164865,E113.428970
Yes, the 'S' letter disappered...
If I use
string = "GPS:3;N23.164865;E113.428970;88"
info = string.tr("GPS:",'')
info_array = info.split(";")
puts "GPS: #{info_array[0]},#{info_array[1]},#{info_array[2]}"
, it prints expected result
GPS: 3,N23.164865,E113.428970
I am very confused why this happens. Can you help?
It looks like you were expecting String#tr to behave like String#gsub.
Calling string.tr("GPS:", '') does not replace the complete string "GPS:" with the empty string. Instead, it replaces any character from within the string "GPS:" with an empty string. Commonly you will find .tr() called with an equal number of input and replacement characters, and in that case the input character is replaced by the output character in the corresponding position. But the way you have called it with only the empty string '' as its translation argument, will delete any of G, P, S, : from anywhere within the string.
>> "String with S and G and a: P".tr("GPS:", '')
=> "tring with and and a "
Instead, use .gsub('GPS:', '') to replace the complete match as a group.
string = "GPS:3;S23.164865;E113.428970;88"
info = string.gsub('GPS:', '')
info_array = info.split(";")
puts "GPS: #{info_array[0]},#{info_array[1]},#{info_array[2]}"
# prints
GPS: 3,S23.164865,E113.428970
Here we've called .gsub() with a string argument. It is probably more often called with a regexp search match argument though.

Convert digits in string to ints and then back to string

Say I have a string: formula = "C3H12O4"
How can I convert the digit chars in the string to ints?
My end goal is to do something along the lines of:
formula * 4
Once converted formula chars to an int, it would be best to report the result back to a string, thus
outputting as:
"C12H48O16"
formula = "C3H12O4"
Code
p formula.gsub(/\d+/) { |x| x.to_i * 4 }
output
"C12H48O16"
If you had many conversions to do it might be worthwhile to include the following in a benchmark of different methods:
h = (0..9).each_with_object({}) { |n,h| h[n.to_s] = (4*n).to_s }
#=> {"0"=>"0", "1"=>"4", "2"=>"8", "3"=>"12", "4"=>"16",
# "5"=>"20", "6"=>"24", "7"=>"28", "8"=>"32", "9"=>"36"}
Then for each string of interest the following calculation would be performed:
"C3H12O4".gsub(/\d/, h)
#=> "C12H48O16"
"99Ra$32".gsub(/\d/, h)
#=> "3636Ra$128"
This uses the form of String#gsub that employs a hash to make the substitutions.
A variant of this is the following.
"C3H12O4".gsub(/./) { |c| h.fetch(c, c) }
#=> "C12H48O16"
Here gsub matches every character, which it passes to the block to be held by the block variable c. Hash#fetch is then used to look up and return h[c], provided h has a key c. If h does not have a key c, fetch's second argument (c) is returned.
The use of the hash avoids the need to convert back and forth between integers and strings, except in the creation of the hash, of course, but that is done only once.

How to split the string and construct as array of objects in rails?

I have a string like
{"a":1, "b":1, "c":1}{"a":2, "b":2, "c":2}
I wanted to parse the string using
JSON.parse(data)
but I get parse error, so I want to split this and process. How can I split this into two separate data and parse?
I need something like
["{"a":1, "b":1, "c":1}", "{"a":2, "b":2, "c":2}"]
so that I can loop and parse. How can I do this? Please help me. Thanks in advance.
1)Your current string is:
a = '{"a":1, "b":1, "c":1}{"a":2, "b":2, "c":2}'
2)You can use the gsub method to replace some characters, adding some special character $:
b = a.gsub( "}{" , "}${" )
Now b will be:
'{"a":1, "b":1, "c":1}${"a":2, "b":2, "c":2}'
3)Finally you can split on the special character you picked ($).
c = b.split("$")
The value of c will be:
["{"a":1, "b":1, "c":1}", "{"a":2, "b":2, "c":2}"]

copy the lines of a file into hashmap in ruby

I have a file with multiple lines. In each line, there two words and a number, split by a comma - for example a, b, 1. It means that string A and string B have the key as 1. I wrote the below piece of code
File.open(ARGV[0], 'r') do |f1|
while line = f1.gets
puts line
end
end
i'm looking for an idea of how to split and copy the characters and number in such a way that the first two words have the last number as key in the hashmap.
Does this work for you?
hash = {}
File.readlines(ARGV[0]).each do |line|
var = line.gsub(' ','').split(',')
hash[var[2]] = var[0],var[1]
end
This would give:
hash['1'] = ['a','b']
I don't know if you want to store number one as an integer or a string, if it's a integer you're looking for, just do var[2].to_i before storing.
Modified your code a little bit, i think it's shorter this way, if i'm in any way wrong, do let me know.

Way to partially match a Ruby string using Regexp

I'm working on 2 cases:
assume I have those var:
a = "hello"
b = "hello-SP"
c = "not_hello"
Any partial matches
I want to accept any string that has the variable a inside, so b and c would match.
Patterned match
I want to match a string that has a inside, followed by '-', so b would match, c does not.
I am having problem, because I always used the syntax /expression/ to define Regexp, so how dynamically define an RegExp on Ruby?
You can use the same syntax to use variables in a regex, so:
reg1 = /#{a}/
would match on anything that contains the value of the a variable (at the time the expression is created!) and
reg2 = /#{a}-/
would do the same, plus a hyphen, so hello- in your example.
Edit: As Wayne Conrad points out, if a contains "any characters that would have special meaning in a regular expression," you need to escape them. Example:
a = ".com"
b = Regexp.new(Regexp.escape(a))
"blah.com" =~ b
Late to comment but I wasn't able to find what I was looking for.The above mentioned answers didn't help me.Hope it help someone new to ruby who just wants a quick fix.
Ruby Code:
st = "BJ's Restaurant & Brewery"
#take the string you want to match into a variable
m = (/BJ\'s/i).match(string) #(/"your regular expression"/.match(string))
# m has the match #<MatchData "BJ's">
m.to_s
# this will display the match
=> "BJ's"

Resources