views:

33

answers:

1

In Ruby on Rails,I got a string number is made of 3 parts : prefix , counter , suffix

In model Setup:

def self.number
prefix = setup.receipt_prefix.blank? ? "" : setup.receipt_prefix.to_s
counter = setup.receipt_counter.blank? ? "" : setup.receipt_counter+1
suffix = setup.receipt_suffix.blank? ? "" : setup.receipt_suffix.to_s

each individual string shows fine:

puts prefix 

=> \#_

puts counter 

=> 1234

puts suffix 

=> #$@s

but when I add 3 string together, an addition back slash appear :

prefix + counter + suffix

=> \\#_1234\#$@s

how can I escape "#" "\" when I add 3 string together ? like

=> \#_1234#$@s

any Ruby or Rails's helper I can use in the model? thx~~

+1  A: 

The string will look different if you get the value versus print (puts) it out. See the following irb session.

>> a = "\\#_"
=> "\\#_"
>> puts a
\#_
=> nil
>> b = "1234"
=> "1234"
>> puts a + b
\#_1234
=> nil
>> a + b
=> "\\#_1234"

The actual string value has two backslashes in it. But only one shows up if you print the string.

Hitesh
the prefix and suffix is customize by user and store in database, if I need to generate a string combining these three, what can I do to escape all in case some user input some strange value?
Gz Rain
@Hitesh: actually, no, the actual string has only one backslash, but it is escaped when `inspect`ing a string.
Mladen Jablanović
@Gz Rain: You don't have to escape anything if you are using parametrized queries, or ORM (which you do, if you are using ActiveRecord). ORM will do all the needed escaping for you.
Mladen Jablanović