添加具有唯一分隔符的数组的最后一个索引

Add the last index of an array with a unique seperator

我试图让数组的最后一个字符与其自身的字符相连接。我在尝试自己解决这个问题时遇到了麻烦,我仍然不熟悉 ruby 上的内置方法。这是我目前所在的位置:

def list(names)
#last = names.last
joined = names.map(&:values).flatten.join(", ")
#joined.pop
#joined << last.join(" &")
end

我想做的是最后一个索引,我想用它自己的字符加入它。我已经尝试这样做了几个小时,但我不断收到错误。如果有人能指出我正确的方向,我将不胜感激。

我的输出目标是

list([{name: 'Bart'},{name: 'Lisa'},{name: 'Garry'}])

输出:

"Bart, Lisa & Gary"

这是一个使用牛津逗号的解决方案,我更喜欢:)

def list(name_list)
  *names, last = name_list.flat_map(&:values)
  oxford_comma = names.size > 1 ? ", " : ""
  names.join(", ") + oxford_comma + "& #{last}"
end

(注意:如果这是 Rails,Array#to_sentence 会自动执行此操作。)

根据您的输入,这是一个可以产生您想要的输出的解决方案:

def list(names)
    *head, tail = names.map(&:values)
    [head.join(", "), tail].join(" & ")
end

尽情享受吧!

我建议创建所有名称都用逗号分隔的字符串(例如,"Bart, Lisa, Garry"),然后用“&”替换最后一个逗号。这里有两种方法。

代码

def list1(names)
  all_commas(names).tap { |s| s[s.rindex(',')] = ' &' }
end

def list2(names)
  all_commas(names).sub(/,(?=[^,]+\z)/, ' &')
end

def all_commas(names)
  names.map(&:values).join(', ')
end

例子

names = [{ name: 'Bart' }, { name: 'Lisa' } , { name: 'Garry' }]

list1 names
  #=> "Bart, Lisa & Garry"

list2 names
  #=> "Bart, Lisa & Garry"

说明

步骤如下

对于all_commas:

a = names.map(&:values)
  #=> [["Bart"], ["Lisa"], ["Garry"]]
a.join(', ')
  #=> "Bart, Lisa, Garry"

对于list1

s = all_commas(names)
  #=> "Bart, Lisa, Garry"
i = s.rindex(',')
  #=> 10
s[i] = ' &'
  #=> " &"
s #=> "Bart, Lisa & Garry"

tap 的区块 returns s

对于list2

a = all_commas(names)
  #=> "Bart, Lisa, Garry"
a.sub(/,(?=[^,]+\z)/, ' &')
  # => "Bart, Lisa & Garry"

使用正面前瞻的正则表达式读取"match a comma, followed by one or more characters other than comma, followed by the end of the string"。