Interacting programmatically with the equivalent of puts -ruby - ruby-on-rails

I have a string, that I need to save escaped and then need to interact with programmatically without any backspaces:
string = 'first=#{first_name}&last=#{last_name}'
p string.to_s
=> "first=\#{first_name}&last=\#{last_name}"
puts string.to_s
=> first=#{first_name}&last=#{last_name}
How do I get first=#{first_name}&last=#{last_name} to assign to a variable that I can scan, that does not have the "\" character?

These two are equivalent:
# double quotes
"first=\#{first_name}&last=\#{last_name}"
# single quotes
'first=#{first_name}&last=#{last_name}'
In neither case is the backslash actually part of the string. If say string.include? '\' it will return false.
However, if you were to say '\#{}' the backslash would be part of the string. That's because in single quotes, #{} does not interpolate but is interpreted as literal characters.
Some example:
foo = 1
'#{foo}' # => "\#{foo}"
"#{foo}" # => "1"
'#{foo}' == "\#{foo}" # => true
"\#{foo}".include? '\' # => false
'\#{foo}'.include? '\' # => true
Note that "\" is an invalid string in ruby, but '\' is valid.

Related

How do I change the separator in parameterize for Rails

This seems like a dumb question, but how do I use parameterize in Rails? I've seen this doc: http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
In my Model I can get string.parameterize to work, but I don't understand how to use the separator param. parameterize(string, separator: '') says I can't use parameterize on main, and string.parameterize(separator: '') says can't implicitly convert from Hash to String
string.parameterize without specifying any character will give you your string separated by words, removing any character that's not a letter, and "joining" them with '-':
string = 'Donald E. Knuth'
string.parameterize
# => "donald-e-knuth"
This way specifying a separator:
string.parameterize(separator: '*')
# => donald*e*knuth
The method acts using the I18n.transliterate method to the passed string, and then applying a destructive gsub! which will check any non-letter character and apply the substitution, is like to do:
# without separator specified
I18n.transliterate(string).gsub!(/[^a-z0-9\-_]+/i, 'separator')
# => Donald-E-Knuth
So this way if there's no separator specified, the method has one already defined as its third parameter:
def parameterize(string, sep = :unused, separator: '-', preserve_case: false)
...
end
Note the use is first the string and then the parameterize method call, unlike what the documentation exemplifies.
Note: Tested on ruby 2.3.1 and Rails 5.0.2 it works well, Rails 4.2.5, 4.2.6 (as you say) and 4.2.7 throws this error:
Loading development environment (Rails 4.2.5)
> string = 'x y z'
# => "x y z"
> string.parameterize(separator: '*')
TypeError: no implicit conversion of Hash into String
In Rails < 5 it must be used as ActiveSupport::Inflector.parameterize(string, separator):
> #item = Item.first
# => #<Item id: 1, name: "new item" ...>
> ActiveSupport::Inflector.parameterize(#item.name, '*')
# => "new*item"
Take a look at this for more info:
parameterize("Donald E. Knuth", separator: '_') # => "donald_e_knuth"
parameterize("^très|Jolie__ ", separator: '_') # => "tres_jolie"
This method comes from the ActiveSupport::Inflector class, so you can do:
ActiveSupport::Inflector.parameterize("Hello World Yeah!", separator: "*")
# => "Hello*World*Yeah!"

How to display "\s" as string in ruby

I want to transform " - " string in Ruby to being translatable to regexp. I need to have something like that:
my_regexp => "\s?-\s?"
However, I have a problem with special characters: This "\s" character isn't shown correctly. I tried few ways. Without success.
INPUT => OUTPUT
"\s?" => " ?"
"\\s?" => "\\s?"
Have you any idea how to solve that?
\\ is just a escaped \.
If you print, puts it, you will see the actual string.
>> '\s' # == "\\s"
=> "\\s"
>> puts '\s'
\s
=> nil
BTW, "\s" (not '\s') is another representation of whitespace " ":
>> "\s" == " "
=> true
Most likely, what you're seeing is the result of how IRB displays values. Your second example is correct, (the actual result only contains a single slash, which you can confirm by creating a new Regexp object from it):
>> "\\s?"
"\\s?"
>> puts "\\s?"
\s?
>> Regexp.new "\\s?"
/\s?/

Regexp union in ruby escapes my original regex

I've got multiple regexes and I want to use Regexp.union to combine them in one big regex so I have this regex to show as an example:
^image\d*$
So I try this :
regex = %w(^image\d*$)
=> ["^image\\d*$"]
re = Regexp.union(regex)
=> /\^image\\d\*\$/
And it escapes my regex to /\^image\\d\*\$/ so when I try the basic case it doesn't match :
"image0".match(re)
=> nil
How can I get arround this?
Pass Regexp object. %w(...) is string literal. Use %r(...) or /.../ for regular expression literal.
regex = %r(^image\d*$)
# => /^image\d*$/
Regexp.union(regex)
# => /^image\d*$/
array_of_regexs = [/a/, /b/, /c/]
# => [/a/, /b/, /c/]
Regexp.union(array_of_regexs)
# => /(?-mix:a)|(?-mix:b)|(?-mix:c)/

How to remove "$" and "," from a price field in Rails

I am saving a price string to my database in a decimal-type column.
The price comes in like this "$ 123.99" which is fine because I wrote a bit of code to remove the "$ ".
However, I forgot that the price may include a comma, so "$ 1,234.99" breaks my code. How can I also remove the comma?
This is my code to remove dollar sign and space:
def price=(price_str)
write_attribute(:price, price_str.sub("$ ", ""))
# possible code to remove comma also?
end
You can get there two ways easily.
String's delete method is good for removing all occurrences of the target strings:
'$ 1.23'.delete('$ ,') # => "1.23"
'$ 123,456.00'.delete('$ ,') # => "123456.00"
Or, use String's tr method:
'$ 1.23'.tr('$, ', '') # => "1.23"
'$ 123,456.00'.tr('$ ,', '') # => "123456.00"
tr takes a string of characters to search for, and a string of characters used to replace them. Consider it a chain of gsub methods, one for each character.
BUT WAIT! THERE'S MORE! If the replacement string is empty, all characters in the search string will be removed.

ruby on rails, replace last character if it is a * sign

I have a string and I need to check whether the last character of that string is *, and if it is, I need to remove it.
if stringvariable.include? "*"
newstring = stringvariable.gsub(/[*]/, '')
end
The above does not search if the '*' symbol is the LAST character of the string.
How do i check if the last character is '*'?
Thanks for any suggestion
Use the $ anchor to only match the end of line:
"sample*".gsub(/\*$/, '')
If there's the possibility of there being more than one * on the end of the string (and you want to replace them all) use:
"sample**".gsub(/\*+$/, '')
You can also use chomp (see it on API Dock), which removes the trailing record separator character(s) by default, but can also take an argument, and then it will remove the end of the string only if it matches the specified character(s).
"hello".chomp #=> "hello"
"hello\n".chomp #=> "hello"
"hello\r\n".chomp #=> "hello"
"hello\n\r".chomp #=> "hello\n"
"hello\r".chomp #=> "hello"
"hello \n there".chomp #=> "hello \n there"
"hello".chomp("llo") #=> "he"
"hello*".chomp("*") #=> "hello"
String has an end_with? method
stringvariable.chop! if stringvariable.end_with? '*'
You can do the following which will remove the offending character, if present. Otherwise it will do nothing:
your_string.sub(/\*$/, '')
If you want to remove more than one occurrence of the character, you can do:
your_string.sub(/\*+$/, '')
Of course, if you want to modify the string in-place, use sub! instead of sub
Cheers,
Aaron
You can either use a regex or just splice the string:
if string_variable[-1] == '*'
new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end
That only works in Ruby 1.9.x...
Otherwise you'll need to use a regex:
if string_variable =~ /\*$/
new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end
But you don't even need the if:
new_string = string_variable.gsub(/\*$/, '')

Resources