Trip
Trip

Reputation: 27124

How to append a string in Ruby

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

Answers (6)

Usagi
Usagi

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

Andrew Grimm
Andrew Grimm

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

Jakub Hampl
Jakub Hampl

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

Andrew Spiehler
Andrew Spiehler

Reputation: 201

I think params[:id] << "/" should work.

Upvotes: 0

Mike Yockey
Mike Yockey

Reputation: 4593

Shovel operator?

params[:id] << "/"

Upvotes: 1

Wukerplank
Wukerplank

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

Related Questions