Ruby on rails 接受数组中2个可能的键中的任意一个
我有下面的数组Ruby on rails 接受数组中2个可能的键中的任意一个,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有下面的数组 orders: [ { description: order.description, order_number: order.number, specifications: { size: order.size, weight: order.weight } } ]
orders: [
{
description: order.description,
order_number: order.number,
specifications: {
size: order.size,
weight: order.weight
}
}
]
在规范散列中,我希望能够接受size
或dimension
作为键,比如代替
specifications: {size: order.size, weight: order.weight}
做点像
specifications: {size || dimension: order.size, weight: order.weight}
我如何才能做到这一点?哈希是一个类似字典的唯一键及其值的集合。也称为关联数组,它们类似于数组,但当数组使用整数作为索引时,哈希允许您使用其键 嗯,你不能达到上述行为 如果要获取大小或维度的值,可以尝试以下方法
irb(main):011:0> specifications = {size: 10, weight: 20}
=> {:size=>10, :weight=>20}
irb(main):012:0> order_spec = specifications[:size] || specifications[:dimension]
=> 10
irb(main):013:0> order_spec
=> 10
以下是您在使用和之后所做的: 例如 然而,这确实让人感到有点不安:与其尝试调整键,为什么不同时传递这两个键并以不同的方式处理另一端
response = {
orders: [
{
description: order.description,
order_number: order.number,
specifications: {
weight: order.weight,
size: order.size,
dimension: order.dimension
}
}
]
}
然后:
order = response[:orders].first
size_spec = order.dig(:specifications, :size) || order.dig(:specifications, :dimension)
希望这对您有所帮助,让我知道您的进展情况。如果
size
和dimension
键都存在,您想做什么?我相信您对哈希
数据类型的期望比它能给您的要高。在这种情况下,您应该定义自己的数据类型(基于maybe)。这对@CrescentStrike有帮助吗?
response = {
orders: [
{
description: order.description,
order_number: order.number,
specifications: {
weight: order.weight,
size: order.size,
dimension: order.dimension
}
}
]
}
order = response[:orders].first
size_spec = order.dig(:specifications, :size) || order.dig(:specifications, :dimension)