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

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

store the value in array and return the function ruby

问题

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

  1. # 项目包含哈希数组,示例:
  2. item = [{item1},{item2},{item3}]
  3. def function1
  4. item.map( other_class.call ).flatten
  5. end
  6. # 其他类将返回包含字符串的数组
  7. class other_class
  8. def call
  9. # 返回字符串数组的方法
  10. end
  11. end
  12. # 目前,function1 返回一个包含字符串值的数组的数组。
  13. # 期望输出 = ["str1", "str2", "str3", "str4", "str5"]
  14. # 有没有办法修改上述方法?

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}]

  1. def function1
  2. item.map( other_class.call )
  3. end
  4. # other class will return the array which contains string
  5. class other_class
  6. def call
  7. #method which return arrray of strings
  8. end
  9. 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.

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

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

Thanks in advance.

答案1

得分: 1

Output

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

So you should write something like

  1. def function1
  2. other_class.call.flatten
  3. end
英文:

Input

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

Code

  1. p item.flatten

output

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

So you should write something like

  1. def function1
  2. other_class.call.flatten
  3. 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:

确定