存储数值在数组中并返回函数 Ruby

huangapple go评论63阅读模式
英文:

store the value in array and return the function ruby

问题

I understand your request. Here's the translated code and the modified function:

# 项目包含哈希数组,示例:
item = [{item1},{item2},{item3}]

def function1
   item.map( other_class.call ).flatten
end

# 其他类将返回包含字符串的数组
class other_class
   def call
     # 返回字符串数组的方法
   end
end

# 目前,function1 返回一个包含字符串值的数组的数组。

# 期望输出 = ["str1", "str2", "str3", "str4", "str5"]

# 有没有办法修改上述方法?

The modification to the function1 method involves adding the .flatten method to the result of item.map(other_class.call) to convert the array of arrays into a flat array of strings. This will give you the expected output.

英文:

item has array of hash. ex.
item = [{item1},{item2},{item3}]

def function1
   item.map( other_class.call )
end

# other class will return the array which contains string
class other_class
   def call 
     #method which return arrray of strings
   end
end

currently the function1 is returning the array of array which has string values.

function1 output example [["str1"], [], ["str2"], ["str3"], ["str4","str5"]]

I want to modify the function1 which will return the array of string.

expected output = ["str1" "str2", "str3", "str4", "str5"]

Guys, any idea how can I modify the above method.

Thanks in advance.

答案1

得分: 1

Output

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

So you should write something like

def function1
   other_class.call.flatten
end
英文:

Input

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

Code

p item.flatten

output

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

So you should write something like

def function1
   other_class.call.flatten
end

huangapple
  • 本文由 发表于 2023年3月7日 14:58:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658834.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定