I have a string like this:
14.015_KNECHT_178178
How can I split it so that:
art = 14.015
man = KNECHT
As you see the delimeter is _.
Try this
art,man= "14.015_KNECHT_178178".split(/_/)
for more details of #split here
string#split can do this.
>> (art,man,foo) = "14.015_KNECHT_178178".split '_'
=> ["14.015", "KNECHT", "178178"]
>> p art
"14.015"
=> "14.015"
>> p man
"KNECHT"
=> "KNECHT"
>> p foo
"178178"
=> "178178"
Related
How to break the string into two lines in ruby code?
Is there specific symbol?
def my_def
path = "//div/p[contains(., 'This is a veeeeeeeryyyyyy looooonggggg string')]"
end
I wish to make something like that:
def my_def
path = "//div/p[contains(., 'This is a veeeeeeeryyyyyy
looooonggggg string')]"
end
Back slashes doesn't work right!
Ruby will automatically concatenate two strings that are adjacent:
foo = 'a' 'b'
foo # => "ab"
Normally a line-end signifies the end of the assignment:
foo = 'a'
'b'
foo # => "a"
so you can't simply break the lines and expect Ruby to figure out what to do.
\ marks the line as continuing, so you could use:
foo = "a" \
"b"
foo # => "ab"
Or, rely on the + String concatenation:
foo = 'a' +
'b'
foo # => "ab"
I'd probably use the + since it's most often used to join strings already, so its meaning is very obvious. Using \ leads to people joining really long expressions instead of breaking them down.
If your strings are really long, you can use some other tricks:
foo = [
'foo',
'bar'
].join
foo # => "foobar"
If you want to join the strings with a space, such as recombining sentences:
foo = [
'foo',
'bar'
].join(' ')
foo # => "foo bar"
or:
foo = [
'foo',
'bar'
] * ' '
foo # => "foo bar"
Building on all that, I'd use some combination of the above or simply something like:
long_str = 'This is a veeeeeeeryyyyyy' +
' looooonggggg string'
path = "//div/p[contains(., '#{ long_str }')]"
or:
long_str = [
'This is a veeeeeeeryyyyyy',
'looooonggggg string'
].join(' ')
path = "//div/p[contains(., '%s')]" % long_str
You can use a backward slash to indicate the string continues on the next line, like so:
str = "this is a long \
string"
print str # => this is a long string
If your string gets way too big, it might be a good idea to use here docs instead. They allow you to write pieces of text in the middle of the code:
str = <<HEREDOC
This is my string :)
Let's imbue code in the imbued doc: #{[4, 2, 3, 1].sort}
HEREDOC
print str
# => This is my string :)
# => Let's imbue code in the imbued doc: [1, 2, 3, 4]
HEREDOC can be any name you want to give it. You can learn more about here docs here.
I have several strings that look like this:
"((String1))"
They are all different lengths. How could I remove the parentheses from all these strings in a loop?
Do as below using String#tr :
"((String1))".tr('()', '')
# => "String1"
If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:
s = "((String1))"
s = s[2...-2]
p s # => "String1"
If you want to remove all parentheses from the string you can use the delete method on the string class:
s = "((String1))"
s.delete! '()'
p s # => "String1"
For those coming across this and looking for performance, it looks like #delete and #tr are about the same in speed and 2-4x faster than gsub.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
Using String#gsub with regular expression:
"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "
This will remove surrounding parentheses only.
"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "
Here is an even shorter way of achieving this:
1) using Negative character class pattern matching
irb(main)> "((String1))"[/[^()]+/]
=> "String1"
^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )
Or with global substitution "AKA: gsub" like others have mentioned.
irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"
Use String#delete:
"((String1))".delete "()"
=> "String1"
I'm having difficulty reading a file with escaped characters in Ruby...
My text file has the string "First Line\r\nSecond Line" and when I use File.read, I get a string back that escapes my escaped characters: "First Line\r\nSecond Line"
These two strings are not the same things...
1.9.2-p318 :006 > f = File.read("file.txt")
=> "First Line\\r\\nSecond Line"
1.9.2-p318 :007 > f.count('\\')
=> 2
1.9.2-p318 :008 > f = "First Line\r\nSecond Line"
=> "First Line\r\nSecond Line"
1.9.2-p318 :009 > f.count('\\')
=> 0
How can I get the File.read to not escape my escaped characters?
Create a method to remove all the additional escape characters that the File.Read method added, like this:
# Define a method to handle unescaping the escape characters
def unescape_escapes(s)
s = s.gsub("\\\\", "\\") #Backslash
s = s.gsub('\\"', '"') #Double quotes
s = s.gsub("\\'", "\'") #Single quotes
s = s.gsub("\\a", "\a") #Bell/alert
s = s.gsub("\\b", "\b") #Backspace
s = s.gsub("\\r", "\r") #Carriage Return
s = s.gsub("\\n", "\n") #New Line
s = s.gsub("\\s", "\s") #Space
s = s.gsub("\\t", "\t") #Tab
s
end
Then see it in action:
# Create your sample file
f = File.new("file.txt", "w")
f.write("First Line\\r\\nSecond Line")
f.close
# Use the method to solve your problem
f = File.read("file.txt")
puts "BEFORE:", f
puts f.count('\\')
f = unescape_escapes(f)
puts "AFTER:", f
puts f.count('\\')
# Here's a more elaborate use of it
f = File.new("file2.txt", "w")
f.write("He used \\\"Double Quotes\\\".")
f.write("\\nThen a Backslash: \\\\")
f.write('\\nFollowed by \\\'Single Quotes\\\'.')
f.write("\\nHere's a bell/alert: \\a")
f.write("\\nThis is a backspaces\\b.")
f.write("\\nNow we see a\\rcarriage return.")
f.write("\\nWe've seen many\\nnew lines already.")
f.write("\\nHow\\sabout\\ssome\\sspaces?")
f.write("\\nWe'll also see some more:\\n\\ttab\\n\\tcharacters")
f.close
# Read the file without the method
puts "", "BEFORE:"
puts File.read("file2.txt")
# Read the file with the method
puts "", "AFTER:"
puts unescape_escapes(File.read("file2.txt"))
You could just hack them back in.
foo = f.gsub("\r\n", "\\r\\n")
#=> "First Line\\r\\nSecond Line"
foo.count("\\")
#=> 2
I've failed to work out how I can print and display white space characters as something that I can actually 'see'. So for example,
x = "123\n"
print x
I'd like the output to be
123\n
rather than
123
.
The above '.' represents the new line created by '\n'.
s = "abc\ndef"
p s
# >> "abc\ndef"
# it's equivalent to
puts s.inspect
# >> "abc\ndef"
You can do:
x = "123\n"
p x
#=> "123\n"
This method is documented in the Kernel module.
irb(main):003:0> x='123\n'
=> "123\\n"
irb(main):004:0> puts x
123\n
Works for me. Single quoted strings are unescaped, whilst double quoted strings are. To illustrate the difference, I've put the double quoted version below as well:
irb(main):001:0> x="123\n"
=> "123\n"
irb(main):002:0> puts x
123
=> nil
How do I add a apostrophe at the beginning and end of a string?
string = "1,2,3,4"
I would like that string to be:
'1','2','3','4'
Not sure, if this is what you want:
>> s = "1,2,3,4"
>> s.split(',').map { |x| "'#{x}'" }.join(',')
=> "'1','2','3','4'"
result = []
"1,2,3,4".split(',').each do |c|
result << "'#{c.match /\d+/}'"
end
puts result.join(',')
'1','2','3','4'
We can use regular expression to find digits
string = "1,2,3,4"
string.gsub(/(\d)/, '\'\1\'')
#=> "'1','2','3','4'"
str.insert(0, 'x')
str.insert(str.length, 'x')
After seeing your edit.
q = "1,2,3,4"
ar = q.split(',')
ar.each{|i| i.insert(0, "'").insert(-1, "'")}
q = ar.join(',')