1. 字符串 双引号字符串,他寻找以反斜线开始的序列,并以二进制替换他们,如\n,会以换行符代替

puts "And good night,\nGrandma" 输出: And good night, Grandma

字符串表达式内插

{表达式},会以表达式的值替换,例如:

def say_goodnight(name) result = "Good night, #{name}" return result end puts say_goodnight('Pa') 输出: Good night, Pa

任意复杂的表达式都允许放在#{....}表达式中

def say_goodnight(name) result = "Good night, #{name.capitalize}" return result end puts say_goodnight('uncle') 输出: Good night, Uncle

为了方便,如果表达式只是一个全局实例或者类变量,则不需要花括号

$greeting = "Hello" # $greeting is a global variable @name = "Prudence" # @name is an instance variable puts "#$greeting, #@name" 输出: Hello, Prudence

  1. 数组和散列

a = [ 1, 'cat', 3.14 ] # 3个元素的数组

访问第一个元素

a[0] → 1

设置第三个元素

a[2] = nil

显示这个数组

a → [1, "cat", nil]

按上面那个创建数组,要处理很多引号和逗号,很麻烦,用%w可以很方便完成创建数组

a = [ 'ant', 'bee', 'cat', 'dog', 'elk' ]

a[0] → "ant"

a[3] → "dog"

下面实现同样功能:

a = %w{ ant bee cat dog elk }

a[0] → "ant"

a[3] → "dog"

散列如下:

inst_section = { 'cello' => 'string', 'clarinet' => 'woodwind', 'drum' => 'percussion', 'oboe' => 'woodwind', 'trumpet' => 'brass', 'violin' => 'string' }

=>左边是key,右边是对应的value

inst_section['oboe'] → "woodwind" inst_section['cello'] → "string" inst_section['bassoon'] → nil