Tech Talk

Bytefull of Tech Talk (http://tech.bytefull.com)

Little Things about Ruby Strings

Here are some things about Ruby Strings that may have escaped your attention - if you were introduced to Ruby via Rails

Efficiency

Since Ruby scans double-quoted strings for variables and escape sequences, it’s more efficient to use single-quotes for raw strings:

@sentence = 'Jackdaws love my big sphinx of quartz'
redirect_to :index => 'action'

Pretty Please, with sugar on top …

Split your strings across multiple lines. No backslashes required (sorry, couldn’t resist that !).

sql_query = "SELECT [column]
                 FROM [table]
                 WHERE [condition]
-- sql comment goes here"

or

# Q = double-quotes, embed variables 
# q = single-quotes
sql_query = %Q{SELECT @columnname
                 FROM @tablename
                 WHERE @conditions}
# You may use [ < or (as delimiters instead of {

ASCII code

To obtain the ASCII code for a character, prefix it with a question-mark:

puts ?B
# => 66

Convert it back to a string with:

puts 66.chr
# => "B"

Concatenation

Use the << operator to concatenate strings. Where += or + create a new copy, << appends to an existing string. Hence, it is more efficient:

existing << " end"

Instead of:

existing += " end"

(source)

Index a string with a regexp

You can test a string like this:

email = "spamandbakedbeans@skit.org"
if email[/@/]
  puts "I found the first @"
end

And this replaces the first match

string = "jackdaws love my big sphinx of quartz"
string[/a/] = 'A'
# => jAckdaws love my big sphinx of quartz

This replaces the second match

string = "jackdaws love my big sphinx of quartz"
string[/(j).+(z)/, 2] = "Z"
# => jackdaws love my big sphinx of quartZ

Remember, the regexp matches the entire string

Convert hex to integer (sort of)

Given a string representation of a hexadecimal, String.hex returns the corresponding integer:

puts "0x7b".hex # you can omit 0x if you wish
# => 123

Multiply a string

puts "<br />" * 3
# => "<br /><br /><br />"
August 6th, 2007 | ahsan | Rails, Ruby

2 Responses to “Little Things about Ruby Strings”

  1. Stephan Says:

    Hi,

    well the efficiency gain between double and single quoted Strings - it’s hard to measure easily. Take for example this:

    require ‘benchmark’
    include Benchmark

    LOOP_COUNT = 20000000

    bm(12) do |test|
    test.report(”Single quotes:”) do
    LOOP_COUNT.times do |x|
    str = ‘Jackdaws love my big sphinx of quartz’
    str = ‘Yet another sentence, and what for? Benchmarking… Oh, dear.’
    str = ”
    end
    end
    test.report(”Double quotes:”) do
    LOOP_COUNT.times do |x|
    str = “Jackdaws love my big sphinx of quartz”
    str = “Yet another sentence, and what for? Benchmarking… Oh, dear.”
    str = “”
    end
    end
    end

    On my machine this yields the following result:

    user system total real
    Single quotes: 12.860000 0.040000 12.900000 ( 12.966023)
    Double quotes: 12.810000 0.040000 12.850000 ( 12.896760)

    And with the benchmarks swapped:

    user system total real
    Double quotes: 12.990000 0.040000 13.030000 ( 13.112319)
    Single quotes: 12.950000 0.040000 12.990000 ( 13.025266)

    Given the minor difference and the 60 Million there’s hardly any difference. That’s … not even a nano second per new String. So I wouldn’t think you should use single quoted Strings for performance.

    Anyway I use both notations to indicate the real difference: If it’s single quoted it’s literally going to be taken ‘as is’ - with the exception of \\ \’ which are replaced in single quoted strings, too.
    If a String is given with double quotes there will be some kind of variable interpolation or what ever else a single quoted String won’t process (e.g. a new line given as \n).

  2. Marcos Ricardo Says:

    Hi ahsan,

    Great job, with simple and objective samples.

    May be you want to contribute with this:
    http://en.wikibooks.org/wiki/Ruby_by_examples

    Feel free to do that, with this and other subjects.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.