Ruby 基础语法

在 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", <
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值