Ruby三元运算符 [英] Ruby ternary operator

查看:160
本文介绍了Ruby三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这两个语句不相等?

Why aren't these two statements equivalent?


  1. 定义吗? foo? foo<< bar:foo = [ bar]

  2. 如果(定义为foo),则foo<< bar else foo = [ bar] end

  1. defined? foo ? foo << "bar" : foo = ["bar"]
  2. if (defined? foo) then foo << "bar" else foo = ["bar"] end

第一个语句:

irb(main):001:0> defined? foo ? foo << "bar" : foo = ["bar"]
=> nil
irb(main):002:0> foo
=> nil
irb(main):003:0> defined? foo ? foo << "bar" : foo = ["bar"]
=> "expression"
irb(main):004:0> foo
=> ["bar"]

第二条语句:

irb(main):001:0> if (defined? foo) then foo << "bar" else foo = ["bar"] end
=> ["bar"]
irb(main):002:0> foo
=> ["bar"]
irb(main):003:0> if (defined? foo) then foo << "bar" else foo = ["bar"] end
=> ["bar", "bar"]
irb(main):004:0> foo
=> ["bar", "bar"]

这些会话与JRuby 1.5.0(应该等效)原生Ruby 1.8.7)。我发现本机红宝石1.9.1的行为略有不同:即使运行两次,语句#1也从未定义 foo

These sessions are with JRuby 1.5.0 (should be equivalent to native Ruby 1.8.7). I see slightly different behavior with native ruby 1.9.1: statement #1 never defines foo even when running it twice.

推荐答案

因为第一个计算结果为:

Because the first evaluates to:

defined?(foo ? foo << "bar" : foo = ["bar"])

为什么返回nil,我有毫无头绪...

Why that returns nil, I have no clue...

解决方法很简单:

(defined? foo) ? foo << "bar" : foo = ["bar"]

这篇关于Ruby三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆