1.单引号还是双引号?
案例:
在某一次项目开始时候,修改了routs.rb中 root :to => 'home#index',自己没意识到错误,结果问题来了,删了public/index.html文件,就是从域名定位不到home下的index,搞了许久才发现,root :to => 'home#index'其实应该是双引号。
为什么呢,其实跟ruby语言的特性有关,ruby中的单引号与双引号的区别就在于,双引号可以解析,而单引号是完整引用
2.%的用法?%w %x,%x( mysqladmin --user=#{MYSQL_DB_USER} create activerecord_unittest )?这是什么意思呢?
%{String} 用于创建一个使用双引号括起来的字符串
%Q{String} 用于创建一个使用双引号括起来的字符串
%q{String} 用于创建一个使用单引号括起来的字符串
%r{String} 用于创建一个正则表达式字面值
%w{String} 用于将一个字符串以空白字符切分成一个字符串数组,进行较少替换
%W{String} 用于将一个字符串以空白字符切分成一个字符串数组,进行较多替换
%s{String} 用于生成一个符号对象
%x{String} 用于执行String所代表的命令
PS:上面几个%表示法中用{}扩住了String,其实这个{}只是一种分割符,可以换成别的字符,比如(),那么%表示法就是%(String),当然还可以是别的字符,对于非括号类型的分割符,左右两边要相同,如%!String!
下面我对这些表示法简单举几个例子:
%{String}用于创建一个使用双引号括起来的字符串
这个表示法与%Q{String}完全一样,这边直接句个例子看结果:
- result = %{hello}
- puts "result is: #{result}, Type is:#{result.class}"
结果:
result is: hello, Type is:String
%Q{String}用于创建一个使用双引号括起来的字符串
%q{String}用于创建一个使用单引号括起来的字符串
从说明中可以看出这两个表示法的区别就是一个使用双引号,一个使用单引号。使用双引号的字符串会对字符串中的变量做较多替换,而单引号则做较少的替换,具体看例子。先看%Q{String}:
- world = "world"
- result = %Q{hello #{world}}
- puts "result is: #{result}, Type is:#{result.class}"
结果:
result is: hello world, Type is:String
换成%q{String}:
- world = "world"
- result = %q{hello #{world}}
- puts "result is: #{result}, Type is:#{result.class}"
结果:
result is: hello #{world}, Type is:String
从上面的结果可以看出,较少替换的情况下,#{world}被解析成了字符串,而不会去计算这个变量中的值。
%r{String}用于创建一个正则表达式字面值
就像使用/reg/方式一样,看代码:
- result = %r{world}
- puts result =~ "hello world"
- puts "result is: #{result}, Type is:#{result.class}"
结果:
6
result is: (?-mix:world), Type is:Regexp
可以看出,world从第6个字符开始匹配
%w{String}用于将一个字符串以空白字符切分成一个字符串数组,进行较少替换
%W{String}用于将一个字符串以空白字符切分成一个字符串数组,进行较多替换
这两个应该是大家见过最多的,用这个方式构造数组,可以省下一些逗号,Ruby真是会惯坏大家,以后大家都不用标点符号了。
同样给一个简单的例子:
- result = %w{hello world}
- puts "result is: #{result}, Type is:#{result.class}, length is:#{result.length}"
结果:
result is: helloworld, Type is:Array, length is:2
%s{String}用于生成一个符号对象
直接先上代码:
- result = %s{hello world}
- puts "result is: #{result}, Type is:#{result.class}"
- sym = :"hello world"
- puts "the two symbol is the same: #{sym == result}"
结果:
result is: hello world, Type is:Symbol
the two symbol is the same: true
可以看出,这两中方式生成的symbol对象完全一样
%x{String}用于执行String所代表的命令
比如:
%x{notepad.exe}可以启动windows下的记事本,这里我就不列结果了(那是一个大家熟悉的窗口)。大家自己试试看
来自:http://www.iteye.com/topic/440195
3.想要创建一个含有Ruby变量值或者表达式值的字符串。
解决方案 Solution
在字符串中,将变量或者表达式用花括号围住,并用井号作为前缀。
number = 5
“This number is #{number}.“ #=>“This number is 5.“
“This number is #{5}.“ #=>“This number is 5.“
“This number after #{number} is #{number.next}.”
#=>“This number after 5 is 6.”
“This number prior to #{number} is #{number -1}.”
#=>“This number prior to 5 is 4.”
“We are ##{number}!” #=>”We are #5!”