为什么有这么多略微不同的方法在Ruby中做同样的事情?

Rya*_*ela 11 ruby timtowtdi

我正在学习Ruby.我的背景是C++/Java/C#.总的来说,我喜欢这种语言,但我有点困惑为什么有很多不同的方法来完成同样的事情,每种方法都有自己略有不同的语义.

例如,创建字符串.我可以使用'',",q%,Q%或只是%来创建字符串.某些形式支持插值.其他形式允许我指定字符串分隔符.

为什么有五种方法来创建字符串文字?为什么我会使用非插值字符串?%语法比引用文字有什么优势?

我知道Ruby中的redundency一定有价值,但是我未经训练的眼睛并没有清楚地看到它.请赐教.

Joh*_*lla 15

为什么我会使用非插值字符串?

当然,当你不想要插值时.例如,也许你正在输出一些关于字符串插值的文档:

'Use #{x} to interpolate the value of x.'
=> "Use #{x} to interpolate the value of x."
Run Code Online (Sandbox Code Playgroud)

%语法比引用文字有什么优势?

它允许您更自然地编写字符串,不带引号,或者当您不想逃避很多事情时,类似于C#的字符串 - 字面值前缀@.

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

%{<basket size="50">}
=> "<basket size=\"50\">"
Run Code Online (Sandbox Code Playgroud)

还有许多其他%注释:

%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"
Run Code Online (Sandbox Code Playgroud)

还有%s(用于符号)和其他一些.

为什么有五种方法来创建字符串文字?

这不是特别不寻常.考虑C#,例如,它有几种不同的方式来生成字符串:new String(); ""; @""; StringBuilder.ToString()等等.

  • "自然"是非常主观的."非常不寻常"并不是创造语言特征的动力. (2认同)
  • “自然”是非常主观的,但“更少、更容易输入的字符来表达完全相同的事情”却不是,并且是创建语言功能的一个很好的动机。 (2认同)