学习了一段时间的Ruby on Rails,用它做了一些小东西,开始是直接看的《Agile Web Development with Rails 2nd》虽然很多东西做出来了,但是依然有些不懂的地方,所以现在回过头来好好看看Ruby的书。
在ruby中所有的事物都是对象,String也不例外,含有两个同样值的字符串其实是两个object,
a = "string"
b = "string"
c = a
puts a.object_id
puts b.object_id
puts c.object_id
#输出:
#
#21676710
#21676690
#21676710
字符串的连接:
a ="hello,"
b ="world!"
puts a+b
puts a<<b
#输出:
#hello,world!
#hello,world!
如上面的代码示例,可以用 "+"和"<<"进行两个字符串的连接。如果字符串太长在代码里需要换行可以用下面的方法:
a ="hello,\
world!"
b ="hello,"\
+"world!"
puts a
puts b
#输出:
#hello, world!
#hello,world!
上面我们演示了在双引号内和引号外的两种换行连接方式,在这里需要注意,第一种方法输出的结果中"world"字符前面带有空格,这是因为在给a赋值时world前有空格,而第二行的格式是包含在引号内的。
双引号和单引号的区别:
双引号内支持更多的转义字符 比如\n
a ="hello,\nworld!"
b ='hello,\nworld!'
puts a
puts b
#输出:
#hello,
#world!
#hello,\nworld!
双引号内还支持表达式
a = "jack"
puts "who is #{a}"
#输出:
#who is jack
表达式以#{expression}的形式插入双引号内输出表达式的值。
全局变量和类变量不需要{},如下:
$greeting = "Hello" # $greeting is a global variable
@name = "Prudence" # @name is an instance variable
puts "#$greeting, #@name"
#输出:
#Hello, Prudence
正则表达式:
ruby支持perl 标准的正则表达式,使用符号=~
a = "php is programming language ,ruby too"
puts a if a=~/php.*ruby/
puts a=~/php ruby/
#输出:
#php is programming language ,ruby too
#nil
如果匹配成功则返回匹配的字符在字符串中的位置。
在ruby中还有一些全局变量可以方便的使用,$`返回匹配串前面的字符,$&返回匹配的字符串,$'返回匹配串后面的字符串。
def show_regexp(a, re)
if a =~ re
"#{$`}<<#{$&}>>#{$'}"
else
"no match"
end
end
puts show_regexp('Fats Waller', /a/)
#输出:
#F<<a>>ts Waller