标准库
Strings
字符串嵌入表达式
在ruby中,如果在创建字符常量时使用双引号,那么可以在#{}中嵌入一个表达式,Ruby会自动把表达式的值和字符串连接起来
result = "Good night, #{name.capitalize}"
puts "now is #{ def the(a)
'the ' + a
end
the('time')
} for all good coders..."
对于全局变量有不同的语法
$salutation = 'hello' # Define a global variable
"#$salutation world" # Use it in a double-quoted string
调用底层操作系统命令
`date` # => "Mon Apr 13 13:25:58 CDT 2009\n"
`ls`.split[34] # => "ext_c_win32ole.tip"
%x{echo "Hello there"} # => "Hello there\n"
从第二条可以看到,从操作系统返回的结果是一个String,因此还可以程序交互
长字符
Ruby中用%{}来处理长字符。这个字符中可以放任何格式化的字符。
符号(关键字)
可以把符号看做变量名和变量值相同的变量,这时候不分辨变量名和值。由于值和名字都是相同的,因此甚至不用设置初始值,直接用就可以。
符号用在变量不变且仅仅要用来标示的地方。
1.用在映射中
inst_section = {
:cello => 'string',
:clarinet => 'woodwind',
:drum => 'percussion',
:oboe => 'woodwind',
:trumpet => 'brass',
:violin => 'string'
}
inst_section[:oboe] # => "woodwind"
inst_section[:cello] # => "string"
# Note that strings aren't the same as symbols...
inst_section['cello'] # => nil
2.用在全局标示
def walk(direction)
if direction == :north
# ...
end
end