You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Ruby方法将嵌套字符串数组转为一维字符串数组?

如何将嵌套字符串数组展平为一维数组?

问题描述

现有哈希数组 item = [{item1}, {item2}, {item3}],当前function1方法调用other_class的call方法处理该数组,由于other_class.call返回字符串数组,导致function1输出嵌套字符串数组,例如:

[["str1"], [], ["str2"], ["str3"], ["str4","str5"]]

需要修改function1,使其返回一维字符串数组,预期输出:

["str1", "str2", "str3", "str4", "str5"]

解决方案

以Ruby为例(适配哈希数组场景)

原function1通常是通过map遍历处理每个哈希元素,最终得到嵌套数组:

def function1(items)
  items.map { |item| OtherClass.call(item) }
end

直接改用flat_map方法即可,它会自动将每个子数组展平并合并为一维数组,同时自动忽略空数组:

def function1(items)
  items.flat_map { |item| OtherClass.call(item) }
end

也可以用map加flatten的组合实现(效果一致,但flat_map无需创建中间数组,效率更高):

def function1(items)
  items.map { |item| OtherClass.call(item) }.flatten
end

以JavaScript为例

若场景为JavaScript,原代码可能如下:

function function1(items) {
  return items.map(item => otherClass.call(item));
}

改用flatMap方法实现展平:

function function1(items) {
  return items.flatMap(item => otherClass.call(item));
}

或者用reduce手动合并数组:

function function1(items) {
  return items.reduce((result, item) => result.concat(otherClass.call(item)), []);
}

内容的提问来源于stack exchange,提问作者luffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:22:37