Tech Talk

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

Archives for August, 2007

Little Things about Ruby Strings

August 6th, 2007 by ahsan

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 />"
Filed under Rails, Ruby having 2 Comments »