Ruby有条件地构造JSON

Ruby有条件地构造JSON,ruby,json,Ruby,Json,我想在ruby中创建一个JSON对象,并有条件地添加属性 step_json = { "id" => step.id, "name" => step.name, "position" => step.position, "ancestry" => step.ancestry, "image_path" => (step.first_image.image_path_url || step.first_image.s3_fi

我想在ruby中创建一个JSON对象,并有条件地添加属性

  step_json = {
    "id" => step.id,
    "name" => step.name,
    "position" => step.position,
    "ancestry" => step.ancestry,
    "image_path" => (step.first_image.image_path_url || step.first_image.s3_filepath) if step.first_image.present?,
    "label" => step.label if step.label.present?,
    "label_color" => step.last_color if step.label.present?
  }

我的条件语句有错误。有没有一种方法可以在不对整个step_json对象执行if/else语句的情况下执行此操作?

在创建静态条目后,可以有条件地向对象添加单个条目

step_json = {
  "id" => step.id,
  "name" => step.name,
  "position" => step.position,
  "ancestry" => step.ancestry
}
step_json['image_path'] = (step.first_image.image_path_url || step.first_image.s3_filepath) if step.first_image.present?
step_json['label'] = step.label if step.label.present?
step_json['label_color'] = step.last_color if step.label.present?