在 Ruby 中,一切皆对象,包括字符串和 nil 都是。
字符串
"foo" + "bar" # 字符串拼接
=> "foobar"
first_name = "Michael" # 变量赋值
"#{first_name} Hartl" # 字符串插值 #{变量名}
=> "Michael Hartl"
# 关于单双引号
Ruby 不会对单引号字符串进行插值操作
"foobar".length # 获取字符串长度
=> 6
ruby中自带函数
# 是否为空 empty? 方法
# 注意,empty? 方法末尾有个问号,这是 Ruby 的约定,说明方法返回的是布尔值,即 true 或 false。
"foobar".empty?
=> false
"".empty?
=> true
# if else 用法
if s.nil?
"The variable is nil"
elsif s.empty?
"The string is empty"
elsif s.include?("foo")
"The string includes 'foo'" # 是否包含 'foo'
end
=> "The string includes 'foo'"
# &&(与)、||(或)和 !(非)运算符
x = "foo"
y = ""
puts "Both strings are empty" if x.empty? && y.empty?
=> nil
puts "One of the strings is empty" if x.empty? || y.empty?
=> "One of the strings is empty"
=> nil
puts "x is not empty" if !x.empty?
=> "x is not empty"
=> nil
# to_s 方法基本上可以把任何对象转换成字符串
nil.to_s
=> ""
nil.empty?
NoMethodError: undefined method `empty?` for nil:NilClass
nil.to_s.empty? # 消息串联
=> true
# 测试对象是否为空
"foo".nil?
=> false
"".nil?
=> false
nil.nil?
=> true
# if 关键词 用法 表达式为真值时才执行的语句
# 还有个对应的 unless 关键字也可以这么用
puts "x is not empty" if !x.empty?
string = "foobar"
puts "The string '#{string}' is nonempty." unless string.empty?
nil 对象的特殊性,除了 false 本身之外,所有 Ruby 对象中它是唯一一个布尔值为“假”的。
我们可以使用 !!(读作“bang bang”)对对象做两次取反操作,把对象转换成布尔值:
!!nil
=> false
除此之外,其他所有 Ruby 对象都是“真”值,数字 0 也是:
!!0
=> true
数组
# 字符串转为数组 split
"foo bar baz".split # 把字符串拆分成有三个元素的数组
=> ["foo", "bar", "baz"]
# 根据字符 转化
"fooxbarxbazx".split('x')
=> ["foo", <