ruby on rails replace single-quotes with double-quote in a string
If that's the only case you're covering where you need to show some output in double quoted string then. How about something simple like following
str = "The result of the child is \"#{current_res}\" and the lowest grade is \"#{lowest_res }\" ."
You can escape quotes in double quoted strings.
ruby coding convention for single or double quoting your strings
I don't think there is a strong convention within the entire community. From what I have seen, there seems to be a bias towards ignoring single quotes altogether and always using double quotes. In some circles, that is even a convention, but a localized one, not one for the whole community.
Personally, whenever I have several different ways to express the same thing, I tend to use those different ways to convey different semantics. (For example, I use curly braces vs. do
/end
in blocks to distinguish between blocks that are used for their side effects and blocks that are used for their return value.)
So, I only use double quotes when I actually want to use string interpolation or escaping, otherwise I use single quotes. That way, when I see a string I can immediately tell that there's no funny business going on, and there's no code hidden inside of it.
I am pragmatic, though. I very much prefer "It's a string!"
over 'It\'s a string!'
or %q[It's a string!]
.
Remove double quotes from string
This will do it if you don't want to modify s
:
new_s = s.gsub /"/, '|'
If you do want to modify s
:
s.gsub! /"/, '|'
How to strip leading and trailing quote from string, in Ruby
You could also use the chomp
function, but it unfortunately only works in the end of the string, assuming there was a reverse chomp, you could:
'"foo,bar"'.rchomp('"').chomp('"')
Implementing rchomp
is straightforward:
class String
def rchomp(sep = $/)
self.start_with?(sep) ? self[sep.size..-1] : self
end
end
Note that you could also do it inline, with the slightly less efficient version:
'"foo,bar"'.chomp('"').reverse.chomp('"').reverse
EDIT: Since Ruby 2.5, rchomp(x)
is available under the name delete_prefix
, and chomp(x)
is available as delete_suffix
, meaning that you can use
'"foo,bar"'.delete_prefix('"').delete_suffix('"')
What is the use case for Ruby's %q / %Q quoting methods?
They're extraordinarily useful for escaping HTML with JavaScript in it where you've already "run out" of quoting methods:
link = %q[<a href="javascript:method('call')">link</a>]
I've also found them to be very useful when working with multi-line SQL statements:
execute(%Q[
INSERT INTO table_a (column_a)
SELECT value
FROM table_b
WHERE key='value'
])
The advantage there is you don't need to pay attention to the type of quoting used within your query. It will work with either single, double, or both. They're also a lot less fuss than the HEREDOC style method.
Ruby provides other convenience methods like this such as %r
which can construct regular expressions. That avoids slash-itis when trying to write one that handles stuff like http://
that would otherwise have to be escaped.
how Remove double quotes from a string ruby on rails?
str = 'hello " 5," world'
str.gsub!('"', '')
puts str #hello 5, world
Replace single quote with backslash single quote
The %q delimiters come in handy here:
# %q(a string) is equivalent to a single-quoted string
puts "Cote d'Ivoir".gsub("'", %q(\\\')) #=> Cote d\'Ivoir
Ruby escape double quotes
Use heredoc, it even reads better:
iframe_name = page.execute_script <<JS
$('#card-element').find('[name*="__privateStripeFrame"]').first().attr('name')
JS
Remove quotes from string built from an array
You could use a regular expression:
# match (in a non-greedy way) characters up to a comma or `]`
# capture each word as a group, and don't capture `,` or `]`
str.scan(/'(.+?)'(?:,|\])/).flatten
Or JSON.parse
(but accounting for the fact that single quotes are in fact technically not allowed in JSON):
JSON.parse( str.tr("'", '"') )
JSON.parse
probably has a small edge over the regexp in terms of performance, but if you're expecting your users to do single quote escaping, then that tr
is going to mess things up. In this case, I'd stick with the regexp.
Related Topics
Ruby on Rails: Create Confirmation View Before Creating the Object
"/#Action" Route in Routes.Rb in Ruby on Rails
Uploading a File to a S3 Presigned Url
Loop Within Loop in Rails Controller
Ruby Selenium Web Driver: How to Count Child Element Nodes of a Specific Node
Confused with Ruby Accessor Methods
How to Dry Up Method with Multiple { 'Not Found' }
How to Implement Editing/Formating Text Area in Rails
Rails Adding Multiple Objects to an Empty Array
How to Specify Formatting Options for To_Yaml in Ruby
How to Split String into 2 Parts After Certain Position
Rails: Organizing Models in Subfolders Having Warning: Toplevel Constant a Referenced by B::A
Ruby - Convert Integer to String
How to Interpolate a Variable in a Ruby Regex
When Should I Use Datetime VS Date, Time Fields in Ruby/Rails