ruby - 三元运算符

标签 ruby conditional-operator

我有一个数组 d = ['foo', 'bar', 'baz'] , 并希望将其元素组合成一个由 , 分隔的字符串和 and 在最后一个元素,这样它将变成 foo, bar and baz .

这是我正在尝试做的事情:

s = ''
d.each_with_index { |x,i|
  s << x
  s << i < d.length - 1? i == d.length - 2 ? ' and ' : ', ' : ''
}

但是解释器报错:

`<': comparison of String with 2 failed (ArgumentError)

但是,它适用于 +=而不是 << ,但是 Ruby Cookbook 说:

If efficiency is important to you, don't build a new string when you can append items onto an existing string. [And so on]... Use str << var1 << ' ' << var2 instead.

没有+=是否可行在这种情况下?

此外,必须有一种比上面的代码更优雅的方法。

最佳答案

你只是少了一些括号:

    d = ['foo', 'bar', 'baz']
    s = ''
    d.each_with_index { |x,i|
      s << x
      s << (i < d.length - 1? (i == d.length - 2 ? ' and ' : ', ') : '')
    }

关于ruby - 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6548030/

相关文章:

ruby-on-rails - Rails API : params' tempfile contains null bites from upload and fails to read, 但如果在本地抓取则读取正常

ruby - 错误 : Error installing gollum: ERROR: Failed to build gem native extension

C从两个数组中获取中间索引,变量初始化和三元运算符

c++ - C++ 中是否可以使用三元运算符在 if 语句中选择比较运算符?

c# - 如何使用 ?字符串关键字

mysql - 对 ActiveRecord setter/getter 方法使用 mysql 函数

ruby-on-rails - Ruby on Rails form_with 未显示错误,卡在服务器端

ruby-on-rails - Rspec Ruby on Rails Controller 问题

java ? : operator in vb. 网络

java - Java中 "?"是什么意思?