Reputation: 27124
I am trying to simply add a '/' at the end of this string. What is the best way to do this?
>> params[:id]
"shirts"
I would like to make params[:id] == "shirts/"
. How do I add a /
at the end of that string?
Upvotes: 11
Views: 26081
Reputation: 2946
"Best" depends largely on your use case but consider the following code:
a = 'shirts'
b = a
params = {}
params[:id] = b
params[:id] << '/'
params[:id] #=> "shirts/"
As we'd expect, <<
has added a slash but...
a #=> "shirts/"
# a has changed too!
So, depending on your level of understanding with these methods, this is a behavior you might not expect. Compare to:
params[:id] += '/'
params[:id] #=> "shirts/"
a #=> "shirts"
# a remains the same
Basically, some methods create new objects and others modify existing ones. We can test this with the object_id method.
str1 = 'a'
str2 = str1
str1.object_id #=> 14310680
str2.object_id #=> 14310680
# Both str1 and str2 point to the same object
Now
str1 << 'b' #=> "ab"
str1.object_id #=> 14310680
str2 #=> "ab"
We've successfully modified str1 without creating a new object and since str2 still points to the same object it also gets the "update". Finally, if we use the +=
method:
str1 #=> "ab"
str1 += '' #=> "ab"
str1.object_id #=> 15078280
str2.object_id #=> 14310680
Notice that we have added nothing to str1 but it still creates a new object.
Upvotes: 4
Reputation: 81691
If you're trying to build a URL this way, you're probably doing it wrong, but I can't tell you the right way to do it.
If you're trying to build a directory path this way, and there's other bits to the path, use something like File.join
. Link to the documentation
Upvotes: 0
Reputation: 40583
Simplest:
params[:id] = params[:id] + '/'
or
params[:id] += '/'
Moar fancy:
params[:id] << '/'
Yet another way to do this:
params[:id].concat '/'
If you really really for some bizzare reason insist on gsub:
params[:id].gsub! /$/, '/'
Upvotes: 22
Reputation: 4176
Like this:
params[:id] + '/' == 'shirts/'
No gsub needed :)
Unless you there might be a trailing slash in some cases. Then use:
params[:id] = params[:id] + '/' unless params[:id].match(/.*\/$/)
params[:id] == 'shirts/'
Upvotes: 1