If you have a problem or need to report a bug please email : support@dsprobotics.com
There are 3 sections to this support area:
DOWNLOADS: access to product manuals, support files and drivers
HELP & INFORMATION: tutorials and example files for learning or finding pre-made modules for your projects
USER FORUMS: meet with other users and exchange ideas, you can also get help and assistance here
NEW REGISTRATIONS - please contact us if you wish to register on the forum
Users are reminded of the forum rules they sign up to which prohibits any activity that violates any laws including posting material covered by copyright
[Ruby] Concatenating strings
[Ruby] Concatenating strings
You may know that you can concatenate strings with a plus sign.
Code: Select all
"were" + "wolf" # => "werewolf"Code: Select all
"were" << "wolf" # => "werewolf"Code: Select all
s1 = "were"
s2 = "wolf"
s3 = s1 + s2 # => "werewolf"Code: Select all
s1 = "were"
s2 = "wolf"
s3 = s1 << s2 # => "werewolf"Code: Select all
s1 = "were"
s2 = "wolf"
s3 = s1 + s2 # => "werewolf"
s1 # => "were"Code: Select all
s1 = "were"
s2 = "wolf"
s3 = s1 << s2 # => "werewolf"
s1 # => "werewolf"So what exactly has happened? s1 seems to be the same as s3. Well, if you do an equality check, the result is true.
Code: Select all
s3.equal?(s1) # => trueWhen you concatenate string with the plus sign, behind the scenes a new string is created and s1 and s2 put in there. Then the resulting string object is referenced by s3. But << works in place! It actually extends the object it visually points to. So, s1 << s2 is actually an instruction. Ruby will extend s1 by the content of s2. At that point s1 already reads "werewolf". Then it is referenced by s3. The following code would have had the same effect.
Code: Select all
s1 = "were"
s2 = "wolf"
s1 << s2 # => "werewolf"
s3 = s1 # => "werewolf"Code: Select all
n = 0
s = "were" << n == 1 ? "wolf" : "cat" # => "werecat"
n = rand(2)
s = "were" << case n
when 0
"goose"
when 1
"wolf"
when 2
"cat"
endRe: [Ruby] Concatenating strings
Re: [Ruby] Concatenating strings
Re: [Ruby] Concatenating strings
- wlangfor@uoguelph.ca
- Posts: 912
- Joined: Tue Apr 03, 2018 5:50 pm
- Location: North Bay, Ontario, Canada
- Contact:
Re: [Ruby] Concatenating strings
I was working on a different style of project.
Printed the page as a pdf thanks
Re: [Ruby] Concatenating strings
I do find your occasional mini-tutorials really useful, and so well explained.
So many thanks…
Spogg