Ruby 三元内部哈希构建

问题描述 投票:0回答:3

寻找一种在哈希赋值中包含三元条件的方法。

a = 5
h = {}
h[:alpha] => a > 3 ? true : false  # edited twice
h[:alpha] => (a > 3 ? true : false)    # edited twice

必须有一种方法来缩短这个时间。

ruby hash ternary
3个回答
4
投票

几乎总是当初学者使用文字

true
false
时,这是不必要的。在这种情况下,您根本不需要三元。

a = 5
h = {}
h[:alpha] = a > 3
h[:alpha] # => true

3
投票

您需要使用

=
(赋值运算符)而不是
=>
来分配值。

尝试:

h[:alpha] = a > 3 ? true : false

示例:

2.1.2-perf :001 > a = 5
 => 5
2.1.2-perf :002 > h = {}
 => {}
2.1.2-perf :005 > h[:alpha] = (a > 3 ? true : false)
 => true
2.1.2-perf :006 > h[:alpha]
 => true

编辑(根据您的评论):

2.1.2-perf :014 > user = [1,2,3,4,5]
 => [1, 2, 3, 4, 5]
2.1.2-perf :016 > user[1] == "solo" ? "#{user[2]} #{user[3]} (s)" : "#{user[4]} (g)"
 => "5 (g)"

0
投票

您可以使用 splats:

{
  a: 1,
  **(true ? { b: 2 } : {})
}

# => { a: 1, b: 2 }

© www.soinside.com 2019 - 2024. All rights reserved.