How to print a string with a backward slash in Ruby - ruby

I have a string str = "xyz\123" and I want to print it as is.
The IRB is giving me an unexpected output. Please find the same below:-
1.9.2p290 :003 > str = "xyz\123"
=> "xyzS"
1.9.2p290 :004 >
Any ideas on how can I get IRB to print the original string i.e. "xyz\123".
Thank you..
UPDATE :
I tried escaping it , but it doesn't seem to be that simple for some reason. Please find below my trials with the same:
1.9.2p290 :004 > str = "xyz'\'123"
=> "xyz''123"
1.9.2p290 :005 > str = "xyz'\\'123"
=> "xyz'\\'123"
1.9.2p290 :006 > str = "xyz'\\\'123"
=> "xyz'\\'123"
1.9.2p290 :007 >

UPDATED answer:
escape token '\' is always working in plain ruby code, but not always working in "ruby console". so I suggest you write a unit test:
# escape_token_test.rb
require 'test/unit'
class EscapeTokenTest < Test::Unit::TestCase
def test_how_to_escape
hi = "hi\\backslash"
puts hi
end
end
and you will get result as:
hi\backslash
and see #pst's comment.

The backslash character is an escape character. You may have seen "\n" be used to display a new line, and that is why. "\123" evaulates the ASCII code for 83, which is "S". To print a backslash use 2 backslashes. So you could use str = "xyz\\123".

How to print a backslash?
Use 2 backslashes, e.g. "xyz\\123"
Why does "xyz\123" evaluate to "xyzS"?
In a double-quoted string, \nnn is an octal escape.
Thomas, D. (2009) Programming Ruby, p.329
So, octal 123
= (64 * 1) + (8 * 2) + 3
= decimal 83
= ASCII S

It's simple ... try dump function:
mystring = %Q{"Double Quotes"}
p mystring.dump
=> "\"\\\"Double Quotes\\\"\""
p mystring
=>"\"Double Quotes\""

Related

How to count instances of any Unicode letter in my string

Using Ruby 2.4, how do I count the number of instances of a Unicode letter in my string? I'm trying:
2.4.0 :009 > string = "a"
=> "a"
2.4.0 :010 > string.count('\p{L}')
=> 0
but it's displaying 0, and it should be returning 1.
I want to use the above expression rather than "a-z" because "a-z" won't cover things like accented e's.
You could try using String#scan, passing your \p{L} regex, and then chain the count method:
string = "aá"
p string.scan(/\p{L}/).count
# 2
This is a way that does not create a temporary array.
str = "Même temps l'année prochaine."
str.size - str.gsub(/[[:alpha:]]/, '').size
#=> 24
The POSIX bracket expression [[:alpha:]] is the same as \p{Alpha} (aka \p{L}).
Note that
str.gsub(/[[:alpha:]]/, '')
#=> " ' ."

Extract Date from string ruby

I have this string :
Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)
And I want to extract the date which is "06/04/2015". How do i do this in ruby?
I have tried to do something like this:
str[-1..-11]
but didnt work. Any suggestion? Thanks!
str = "Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)"
str.match(/(\d{2}\/\d{2}\/\d{4})/)[0]
#=> "06/04/2015"
This code matches anything that's in the format of 2 numbers/2 numbers/4 numbers and returns it.
If there's a possibility of having XX/XX/XXXX somewhere else in the string, I'd probably use the following code instead:
str = "Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)"
str.match(\(Introduced (\d{2}\/\d{2}\/\d{4})\)$)[0]
#=> "06/04/2015"
This searches for (Introduced XX/XX/XXXX) and grabs the date from that in particular.
Date has a parse method, which happens to just work.
require 'date'
str = "Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)"
p d = Date.parse(str) # => #<Date: 2015-04-06 ((2457119j,0s,0n),+0s,2299161j)>
str[-11..-2] if the position of the date does not change
I agree with Piccolo's comment. Here is a simple regular expression you can try in irb. I recommend experimenting in irb to learn some rudimentary Ruby regular expressions.
For example, /.+([0-9]{2}\/[0-9]{2}\/[0-9]{4}).+/ looks for anything followed by two digits, slash, two digits, slash, four digits, then anything:
$ irb
2.2.0 :001 > s='Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)'
2.2.0 :009 > /.+([0-9]{2}\/[0-9]{2}\/[0-9]{4}).+/ =~ s && $1
=> "06/04/2015"
2.2.0 :010 >
#steenslag's answer looks for valid dates (unlike the other answers), but could still be tripped up:
str = "The first 10 may go 15/15/2015 with Lou (Introduced 06/04/2015)"
Date.parse(str)
#=> #<Date: 2015-05-10 ((2457153j,0s,0n),+0s,2299161j)>
To ensure the date is in the specified format, you could do the following:
require 'date'
def extract_date(str, fmt)
a = str.each_char
.each_cons(10)
.find { |a| Date.strptime(a.join, fmt) rescue nil }
a ? a.join : nil
end
For str as above:
extract_date(str, '%d/%m/%Y')
#=> "06/04/2015"
A second example:
extract_date("15/15/2015", '%d/%m/%Y')
#=> nil

How to replace single blackslash in ruby

I have been trying something like this to replace blackslash with a word:
str ="\"
str.gsub!("\", "\add")
no luck so far. What am I doing wrong? Thanks
The syntax highlighting on Stack Overflow suggests the problem. Your initial backslash isn't escaped!
str.gsub("\\","\\add")
edit for clarification:
2.2.0 :002 > str = "\\"
=> "\\"
2.2.0 :003 > str.gsub("\\","\\add")
=> "\\add"
Try this code
str = "\\"
str.gsub!("\\", "add")
print str
"\" does not exist in a ruby string
str ="RU\BY"
puts str
will print RUBY
You only can use "\\" so the answer is str.gsub!("\\","\\add")

Escape line breaks in puts output

In IRB on Ruby 1.8.7, I have a collection of strings I'm working with that have newlines in them. When these newlines are output, I want to explicitly see the \r and \n characters within my strings. Is there some way to tell puts to escape those characters, or a method similar to puts that will do what I want?
Note that directly evaluating each string isn't satisfactory because I want to be able to do something like this:
=> mystrings.each { |str| puts str.magical_method_to_escape_special_chars }
This is\na string in mystrings.
This is another\n\rstring.
And don't want to have to do this:
=> mystrings[0]
"This is\na string in mystrings."
=> mystrings[1]
"This is another\n\rstring."
...
=> mystrings[1000]
"There are a lot of\n\nstrings!"
I can use the string#dump method:
=> mystrings.each { |str| puts str.dump }
This is\na string in mystrings.
This is another\n\rstring.
According to the Ruby documention for String, string#dump
Produces a version of str with all nonprinting characters replaced by
\nnn notation and all special characters escaped.
1.8.7 :001 > s = "hi\nthere"
=> "hi\nthere"
1.8.7 :002 > p s
"hi\nthere"

Ruby string manipulation, remove first 3 characters and add them to the end of the string

mystring = "svn-myapplication" or mystring = "git-myapplication"
My desired output:
mystring = "myapplications(svn)"
mystring = "myapplication(git)"
Question: The first 3 characters of the string should be moved to the last with enclosed brackets and the "-" should be removed.
I tried to do something like this:
mystring.gsub('svn-','')+"(svn)" but svn might be git, so i want to use the first three characters to be moved to end with "-" removed and brackets enclosed
A regular expression with groups would work well:
mystring.gsub(/^([a-z]+)-(\w+)/, '\2(\1)')
Lets rock'n'roll :)
mystring = "svn-myapplication"
mystring.split('-').rotate.join('(') + ')'
You could use e regular expression but the simplest solution is as follows
mystring = "svn-myapplication"
puts "#{mystring[4..-1]}(#{mystring[0..2]})"
gives
myapplication(svn)
You can use the [] method of Ruby's String class for this:
mystring = "svn-myapplication"
mystring = "#{mystring[4..-1]}(#{mystring[0,3]})"
You can try something like this in irb
1.9.3-p362 :001 > mystring = "svn-myapplication"
1.9.3-p362 :002 > mystring.gsub(mystring[0,3]+'-','')+(mystring[0,3])
I was going to submit this but, at least I can see how to do it better!
def test(s = '')
match = /\w+-/.match(s).to_s
match = match[0..-2]
s.gsub!(/\w+-/, '')
s << "(#{match})"
end # of test

Resources