Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there so many slightly different ways to do the same thing in Ruby?

Tags:

ruby

timtowtdi

I am learning Ruby. My background is C++/Java/C#. Overall, I like the language, but I am a little confused about why there are so many different ways to accomplish the same thing, each with their own slightly different semantics.

Take string creation, for example. I can use '', "", q%, Q%, or just % to create strings. Some forms support interpolation. Other forms allow me to specify the string delimiters.

Why are there five ways to create string literals? Why would I ever use non-interpolated strings? What advantage does the % syntax have over quoted literals?

I know there must be value in the redundency in Ruby, but my untrained eyes are not clearly seeing it. Please enlighten me.

like image 599
Ryan Michela Avatar asked Nov 25 '09 14:11

Ryan Michela


2 Answers

Why would I ever use non-interpolated strings?

When you don't want the interpolation, of course. For example, perhaps you're outputting some documentation about string interpolation:

'Use #{x} to interpolate the value of x.'
=> "Use #{x} to interpolate the value of x."

What advantage does the % syntax have over quoted literals?

It lets you write strings more naturally, without the quotes, or when you don't want to escape a lot of things, analogous to C#'s string-literal prefix @.

%{The % syntax make strings look more "natural".}
=> "The % syntax makes strings look more \"natural\"."

%{<basket size="50">}
=> "<basket size=\"50\">"

There are many other %-notations:

%w{apple banana #{1}cucumber}   # [w]hitespace-separated array, no interpolation
=> ["apple", "banana", "\#{1}cucumber"]

%W{apple banana #{1}cucumber}   # [W]hitespace-separated array with interpolation
=> ["apple", "banana", "1cucumber"]

# [r]egular expression (finds all unary primes)
%r{^1?$|^(11+?)\1+$}
=> /^1?$|^(11+?)\1+$/

(1..30).to_a.select{ |i| ("1" * i) !~ %r{^1?$|^(11+?)\1+$} }
=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

%x{ruby --version} # [s]hell command
=> "ruby 1.9.1p129 (2009-05-12 revision 23412) [x86_64-linux]\n"

There's also %s (for symbols) and some others.

Why are there five ways to create string literals?

This isn't terribly unusual. Consider C#, for example, which has several different ways to generate strings: new String(); ""; @""; StringBuilder.ToString(), et cetera.

like image 176
John Feminella Avatar answered Nov 09 '22 23:11

John Feminella


I'm not a Ruby expert, but had you ever heard the term "syntactic sugar" ? Basically some programing languages offer different syntax to accomplish the same task. Some people could find one way easier than others due to his previous programing/syntax experience.

like image 23
Andres Avatar answered Nov 10 '22 00:11

Andres