DEV Community

Andressa
Andressa

Posted on

Strings in Ruby

Quick index

  1. String Creation
  2. Single and Double quotes
  3. String Manipulation
    1. Escape Characters
    2. Concatenation
    3. Substrings
    4. Methods
  4. Symbols vs Strings
  5. References

String creation

  • A string can be created by using String literal:
greetings = 'hello all!'
Enter fullscreen mode Exit fullscreen mode
  • with String::new you have more options for creating a string, mostly regarding the encoding type you want your string:
greetings = String.new('hello all!', encoding: 'ASCII')
Enter fullscreen mode Exit fullscreen mode
s = <<HEREDOC
This would contain specially formatted text.

That might span many lines
HEREDOC
Enter fullscreen mode Exit fullscreen mode

Note that it is a good way to add snippets of code, specially SQL if you are in the backend connected to the database, for example.

It preserves the original formatting and can have interpolation inside of it as well. Here we have two good examples from Ruby Guides:

type  = "healthy"
table = "food"
query = <<-SQL
SELECT * FROM #{table}
WHERE #{type} = true
SQL
Enter fullscreen mode Exit fullscreen mode
doc = <<-TIME
Current time is #{Time.now}
TIME

print doc  #=> Current time is 2022-06-07 14:51:09 +0000
Enter fullscreen mode Exit fullscreen mode

We can use single quotes to disable the interpolation.

doc = <<-'TIME'
Current time is #{Time.now}
TIME

print doc  #=> Current time is #{Time.now}
Enter fullscreen mode Exit fullscreen mode

Single (hard) and double (soft) quotes

Interpolation: #{ sequence }. We can place any code inside it. It is very useful.

  • We call single quotes as hard quotes because it is not possible to use interpolation within it, nor escape characters.
name = 'all'
print 'hello #{name}!'  #=> hello #{name}!
Enter fullscreen mode Exit fullscreen mode
  • On the other hand, double quotes allows interpolation and to escape chars, and that is why we call it soft quotes.
name = 'all'
print "hello #{name}!"  #=> hello all!
Enter fullscreen mode Exit fullscreen mode

⁉️ For readability, it is recommended to use doble quotes only when the interpolation is present, but there is no problem if you decide to use only double quotes through your code.

String Manipulation

Escape Characters

Some chars have a special meaning. For example, " can terminate a string before the intended. We can add a backslash in front of it to be able to display it in our string.

print "Double quotes: \""  #=> Double quotes: "
Enter fullscreen mode Exit fullscreen mode

Here is a list of some escape sequences:

escape sequences
\b backspace, ASCII 08h (BS)
\t horizontal tab, ASCII 09h (TAB)
\n newline (line feed), ASCII 0Ah (LF)
\v vertical tab, ASCII 0Bh (VT)
\f form feed, ASCII 0Ch (FF)
\r carriage return, ASCII 0Dh (CR)
\e escape, ASCII 1Bh (ESC)
\s space, ASCII 20h (SPC)
\ backslash, \
\nnn octal bit pattern, where nnn is 1-3 octal digits ([0-7])
\xnn hexadecimal bit pattern, where nn is 1-2 hexadecimal digits ([0-9a-fA-F])
\unnnn Unicode character, where nnnn is exactly 4 hexadecimal digits ([0-9a-fA-F])

Concatenation

The same way you can use interpolation to group strings, you can use concatenation.

print 'hello' + ' all' #=> hello all
Enter fullscreen mode Exit fullscreen mode
print 'hello' << ' all' #=> hello all
Enter fullscreen mode Exit fullscreen mode
print 'hello'.concat(' all') #=> hello all
Enter fullscreen mode Exit fullscreen mode

Substrings

We can access substrings by accessing its indexes just like we would do with an array.

"hello"[0]      #=> "h"

"hello"[0..1]   #=> "he"

"hello"[0, 4]   #=> "hell"

"hello"[-1]     #=> "o"
Enter fullscreen mode Exit fullscreen mode

Methods

There is a long list of methods to support you to handle a string. What is important to note is that in general methods ending with a bang mutantes self and returns self.

Methods that do not have a bang, usually, do not mutate and return a new string.

take the methods capitalize and capitalize! as an example:

a = "hello all!"
a.capitalize

print a #=> hello all!

a.capitalize!

print a #=> Hello all!
Enter fullscreen mode Exit fullscreen mode

Best practice is always to pay attention to the return. Some methods like replace does not have a bang, but modifies self either way.

You can take a look at the methods available here

Symbols vs Strings

symbols are stored in memory only once and it makes things faster. Good for use in hashes.

Strings, on the other hand, need to be stored every time it is used because it can change its content.

"string".object_id == "string".object_id  #=> false

:symbol.object_id == :symbol.object_id    #=> true
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)