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")
Related
In a string concatenation, is it possible to include a conditional directly into the statement?
In the example below, I want "my dear" to be concatenated only if the dear list is not empty.
dear = ""
string = "hello" + " my dear" unless dear.empty? + ", good morning!"
But the result is an error: undefined method '+' for true
I know the alternative would be to define an additional variable before this statement but I would like to avoid this.
It is easier and more readable with interpolation instead of concatenation:
dear = ""
string = "hello#{ ' my dear' unless dear.empty? }, good morning!"
In this case, you would be better off using ternary operators.
string = "hello" + (dear.empty? ? "" : " my dear") + ", good morning!"
The syntax goes like
condition ? if true : if false
Here is something cutie
dear = ""
"hello%s, good morning!" % (' my dear' unless dear.empty?)
# => "hello, good morning!"
dear = "val"
"hello%s, good morning!" % (' my dear' unless dear.empty?)
# => "hello my dear, good morning!"
I will share my solution.
2.7.0 :040 > dear = ""
2.7.0 :041 > string = "hello #{dear.empty? ? "World" : dear}, good morning!"
2.7.0 :042 > string
=> "hello World, good morning!"
2.7.0 :043 > dear = "Test"
2.7.0 :044 > string = "hello #{dear.empty? ? "World" : dear}, good morning!"
2.7.0 :045 > string
=> "hello Test, good morning!"
2.7.0 :046 >
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
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\""
So I know in ruby that x.nil? will test if x is null.
What is the simplest way to test if x equals ' ', or ' '(two spaces), or ' '(three spaces), etc?
Basically, I'm wondering what the best way to test if a variable is all whitespace?
If you are using Rails, you can simply use:
x.blank?
This is safe to call when x is nil, and returns true if x is nil or all whitespace.
If you aren't using Rails you can get it from the activesupport gem. Install with gem install activesupport. In your file either require 'active_support/core_ext to get all active support extensions to the base classes, or require 'active_support/core_ext/string' to get just the extensions to the String class. Either way, the blank? method will be available after the require.
"best" depends on the context, but here is a simple way.
some_string.strip.empty?
s =~ /\A\s*\Z/
Regex solution. Here's a short ruby regex tutorial.
If x is all whitespace, then x.strip will be the empty string. So you can do:
if not x.nil? and x.strip.empty? then
puts "It's all whitespace!"
end
Alternatively, using a regular expression, x =~ /\S/ will return false if and only if x is all whitespace characters:
if not (x.nil? or x =~ /\S/) then
puts "It's all whitespace!"
end
a = " "
a.each_byte do |x|
if x == 32
puts "space"
end
end
Based on your comment I think you can extend the String class and define a spaces? method as follows:
$ irb
>> s = " "
=> " "
>> s.spaces?
NoMethodError: undefined method `spaces?' for " ":String
from (irb):2
>> class String
>> def spaces?
>> x = self =~ /^\s+$/
>> x == 0
>> end
>> end
=> nil
>> s.spaces?
=> true
>> s = ""
=> ""
>> s.spaces?
=> false
>>
s.include?(" ")
Examples:
s = "A B C D"
s.include?(" ") #=> true
s = "ABCD"
s.include?(" ") #=> false
Yet another :) string.all? { |c| c == ' ' }
In Ruby 1.8.6 (2007-09-24 patchlevel 111):
str = '\&123'
puts "abc".gsub("b", str) => ab123c
puts "abc".gsub("b", "#{str}") => ab123c
puts "abc".gsub("b", str.to_s) => ab123c
puts "abc".gsub("b", '\&123') => ab123c
puts "abc".gsub("b", "\&123") => a&123c <--- This I want to achieve using temporary variable
If I change str = '\&123' to str = "\&123" it works fine, but I get str from match function, so I cannot specify it manually within parentheses. Is there any way to change the 'string' to "string" behavior?
maybe there is a simpler way, however the code below works
> str = '\&123'
> puts "abc".gsub("b", str.gsub(/\\&/o, '\\\\\&\2\1'))
> => a\&123c
Simple:
str = '\&123' <-- the result of your match function
str = str.gsub(/\\/, '\\\\')
You may also want to take a look here.
#Valentin
-> I meant that str from match was not taken verbatim. Thus another (simpler) solution appeared, that I was not aware of....
"abc".gsub("b") { str } -> a\&123c
Just remove the backslash:
puts "abc".gsub("b", '&123')
There is no need to protect the ampersand with a backslash inside
single-quoted string literals (unlike double-quoted ones).