I am new to Rspec and I am facing a little issue.
text = page.find(:xpath,"some xpath").text
the code line above gets the value from a html element i.e. 15% or any other value under 100, I want to remove % sign from the value after and getting it to use for comparison. Can anybody help on this?
You can use String#sub to replace it:
'15%'.sub('%', '') #=> '15'
You can also use gsub in case there is more than one occurrence:
'15%%%'.gsub('%', '') #=> '15'
Related
First post here so sorry if this is rookie material. I'm trying to hack away a complicated array into a string and I'm having trouble deleting '\' and '"' characters. Any help is appreciated.
Currently I have this:
"\"-6,\", \"\\\"-3-\\\", \\\"1\\\"\", \"\\\"3-\\\", \\\"5\\\"\", \"\\\"7-\\\", \\\"11\\\"\", \"\\\"14-\\\", \\\"15\\\"\", \"\\\"17-\\\", \\\"20\\\"\""
When I'd like to have this:
"-6, -3-, 1, 3-, 5, 7-, 11, 14-, 15, 17-, 20"
Thank you!
You could try using each and removing any non-desired character within every value in the main array, like:
array.each{|x| x.gsub!(/[^0-9-,]/, '') }.to_s.gsub!(',,', ',')
# => ["-6,-3-,1,3-,5,7-,11,14-,15,17-,20"]
This takes the main array and for each value it replaces any character that's not numeric, nor a hyphen nor a comma with '' using the /[^0-9-,]/ regex and the gsub! method, and the second gsub! is to replace the double comma that remains from the first modification.
I know isn't so elegant, but could help you.
Use String#tr instead of gsub, as tr is much faster than gsub:
arr.select { |x| x.tr!('\\\"',''); x unless x.empty? }.join(",")
I assume you have an array like:
Arr = [-6, -3-, 1, 3-, 5, 7-, 11, 14-, 15, 17-, 20]
So try join method:
Arr.join(',')
Hope it helps..
You could use:
myArray.map { |item| item.gsub(/\\|"/, "") }.join(",").gsub(",,", ",")
I am trying to figure out how to replace multiple characters in an array of strings by using multiple wildcards (or some other method if someone knows better.) Each element in the array is a telephone number and date, (ex. 8675309,2015-01-20). I am trying to remove the comma and date only so that each element in the array be the telephone number only
When iterating over each element in the array, I obtained expected results by calling .gsub! when replacing a single character each element.
file_data = ["8675309,2015-01-20"]
puts file_data[0] #=> 8675309,2015-01-20
file_data.each do |s|
s.gsub!(/0/, "X")
end
puts file_data[0] #> 86753X9,2X15-X1-2X
To eliminate the comma and date, I tried simply using wildcards, calling s.gsub!(",****/**/**", ""). Then, this shows unexpected results:
file_data = ["8675309,2015-01-20"]
file_data.each do |s|
s.gsub!(/,****-**-**/, "")
end
puts file_data[0] #> 8675309,2015-01-20
I also tried several other wildcard characters that have been suggested in other threads ('.' and '^'), but the results have not changed.
I am lost on how to eliminate the comma and date in each element while leaving the primary number intact. I thought .gsub! would be the proper method, but am open to any alternatives as well. Any help is appreciated.
At first glance, I might use String#split to get the phone number:
file_data = ["8675309,2015-01-20"]
phone_numbers = file_data.map {|s| s.split(',').first }
phone_numbers[0] #=> "8675309"
Or, if the phone number is always 7 characters, I might get a string subset with []:
file_data.map {|s| s[0,7] }
Or, if you really want to stick with a regular expression:
file_data.each do |s|
s.gsub!(/,.*\z/, '')
end
Which reads as: part of a string starting from the first comma to the end of the string, replace with nothing.
The way you are handling wildcards is excessive. Why are you using wildcards when you know what you want to sub? Removing commas and the date (as long as the date is always the same format) should be simple:
name = "8675309,2015-01-20"
name.gsub!(/,\d{4}-\d{2}-\d{2}/,"")
Use String#partition
name.partition(',')[0]
=>"8675309"
I have a date string that I need to simplify in Ruby:
2008-10-09 20:30:40
I only want the day portion:
2008-10-09
I'm looking for a gsub line that will strip everything after a set number of characters or the first whitespace.
I prefer to use as simple a solution as I can. Using gsub is needlessly complex. Either of these will do it:
str = '2008-10-09 20:30:40'
str[/(\S+)/, 1] #=> "2008-10-09"
str[0, 10] #=> "2008-10-09"
Literal solution:
date.gsub(/(.{10}).*/, '\1')
date.gsub(/\s.*/, '')
date[0, 10]
Better solution: Treat it as a DateTime object - then you can format it as you wish:
date = DateTime.now
date.strftime("%m-%d-%Y") # America
date.strftime("%d-%m-%Y") # Europe
If the format is consistantly like that,
'2008-10-09 20:30:40'[/[-\d]+/] # => "2008-10-19"
'2008-10-09 20:30:40'.split[0]
How can I remove the very first "1" from any string if that string starts with a "1"?
"1hello world" => "hello world"
"112345" => "12345"
I'm thinking of doing
string.sub!('1', '') if string =~ /^1/
but I' wondering there's a better way. Thanks!
Why not just include the regex in the sub! method?
string.sub!(/^1/, '')
As of Ruby 2.5 you can use delete_prefix or delete_prefix! to achieve this in a readable manner.
In this case "1hello world".delete_prefix("1").
More info here:
https://blog.jetbrains.com/ruby/2017/10/10-new-features-in-ruby-2-5/
https://bugs.ruby-lang.org/issues/12694
'invisible'.delete_prefix('in') #=> "visible"
'pink'.delete_prefix('in') #=> "pink"
N.B. you can also use this to remove items from the end of a string with delete_suffix and delete_suffix!
'worked'.delete_suffix('ed') #=> "work"
'medical'.delete_suffix('ed') #=> "medical"
https://bugs.ruby-lang.org/issues/13665
I've answered in a little more detail (with benchmarks) here: What is the easiest way to remove the first character from a string?
if you're going to use regex for the match, you may as well use it for the replacement
string.sub!(%r{^1},"")
BTW, the %r{} is just an alternate syntax for regular expressions. You can use %r followed by any character e.g. %r!^1!.
Careful using sub!(/^1/,'') ! In case the string doesn't match /^1/ it will return nil. You should probably use sub (without the bang).
This answer might be more optimised: What is the easiest way to remove the first character from a string?
string[0] = '' if string[0] == '1'
I'd like to post a tiny improvement to the otherwise excellent answer by Zach. The ^ matches the beginning of every line in Ruby regex. This means there can be multiple matches per string. Kenji asked about the beginning of the string which means they have to use this regex instead:
string.sub!(/\A1/, '')
Compare this - multiple matches with this - one match.
In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead:
>> a = "0123"
=> "0123"
>> a[0]
=> 48
I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it.
Or you can convert the integer to its character value:
a[0].chr
You want a[0,1] instead of a[0].
I believe this is changing in Ruby 1.9 such that "asdf"[2] yields "d" rather than the character code
To summarize:
This behavior will be going away in version 1.9, in which the character itself is returned, but in previous versions, trying to reference a single character of a string by its character position will return its character value (so "ABC"[2] returns 67)
There are a number of methods that return a range of characters from a string (see the Ruby docs on the String slice method) All of the following return "C":
"ABC"[2,1]
"ABC"[2..2]
"ABC".slice(2,1)
I find the range selector to be the easiest to read. Can anyone speak to whether it is less efficient?
#Chris,
That's just how [] and [,] are defined for the String class.
Check out the String API.
The [,] operator returns a string back to you, it is a substring operator, where as the [] operator returns the character which ruby treats as a number when printing it out.
I think each_char or chars describes better what you want.
irb(main):001:0> a = "0123"
=> "0123"
irb(main):002:0> Array(a.each_char)
=> ["0", "1", "2", "3"]
irb(main):003:0> puts Array(a.each_char)
0
1
2
3
=> nil