2015-11-20 98 views
1

我有一对夫妇的Ruby数组:获取数组元素值,而方括号和双引号

array1 = ["a", "b"] 
array2 = ["a", "b", "c"] 
array3 = ["a", "b", "c", "d"] 
array4 = ["a", "b", "c", "d", "e"] 

我需要返回下列字符串:

#array1 
"a" 

#array2 
"a and b" 

#array3 
"a, b and c" 

#array4 
"a, b, c and d" 

数组的最后一个元素应永远不会显示。

我不知道数组中包含多少个元素或这些元素的值。

为了实现我需要什么,我想出了下面的方法:

def format_array(array) 
    if array.length - 1 == 1 
    array[0].to_s 
    elsif array.length - 1 == 2 
    array[0].to_s + " and " + array[1].to_s 
    elsif array.length - 1 > 2 
    array.sort.each_with_index do |key, index| 
     unless key == "e" 
     if index == array.length - 2 
      " and " + array[index].to_s 
     else 
      array[index].to_s + ", " 
     end 
     end 
    end 
    end 
end 

此方法返回与方括号和双引号来代替瘦肉字符串值的数组。例如,我得到["a", "b", "c", "d", "e"]而不是"a, b, c and d"array4

我该如何做这项工作?

+1

你不会在数组的长度的最后返回任何字符串超过2所以返回数组排序为是。在ruby中记住在方法中执行的最后一条语句,并对其进行评估并返回。因此,只需将生成的字符串存储在对象中,并在最后返回。另外,我不知道你为什么要检查'array.length - 1',它应该是'array.length' –

+0

感谢您的评论。按照我最初问这个问题的方式,你的答案是正确的,但用'array.length - 1'检查没有任何意义:我更新了问题以提供更多上下文。基本上,这是因为我从不想显示数组的最后一个元素。 –

回答

5
def join_with_commas_and_and(array) 
    if array.length <= 2 
    array.join(' and ') 
    else 
    [array[0..-2].join(', '), array[-1]].join(' and ') 
    end 
end 

编辑:忽略最后一个元素,添加此行的函数的第一行:

array = array[0..-2] 
+1

高尔夫球的乐趣和利润:'array.push(array.pop(2).join'和').join','' – mwp

+0

非常感谢您的回答Amadan。这实际上是我提出的最初问题的正确答案。但是,你的回答和穆罕默德奥萨马的评论让我意识到我没有提供足够的背景。请原谅我。 –

+0

@mwp:非常好。虽然,这是破坏性的;我试图保持原始数组完好无损。事先克隆它是一个简单的修复,但。 – Amadan

2

我认为这是最容易被忽视'and',直至插入逗号,然后替换最后一个逗号与'and'

def fmt(arr) 
    return arr.first if arr.size == 2 
    str = arr[0..-2].join(', ') 
    str[str.rindex(',')] = ' and' 
    str 
end 
    # ["a", "b"]: a 
    # ["a", "b", "c"]: a and b 
    # ["a", "b", "c", "d"]: a, b and c 
    # ["a", "b", "c", "d", "e"]: a, b, c and d