【问题标题】:Ruby map to append dot at the endRuby映射在末尾附加点
【发布时间】:2020-11-12 19:03:06
【问题描述】:

我有下面一行

new_records = records.map{|record| record.name.to_s.}.sort

哪个输出

# Current Output:

new_records = ["ab-12.cd.net", "de-34.fg.net"]

我怎样才能让它以.(点)结尾?

# Desired Output:

new_records = ["ab-12.cd.net.", "de-34.fg.net."]

例如,我可以使用另一张地图来做到这一点

new_records = records.map{|record| record.name.to_s.}.sort
new_records2 = new_records.map { |record| "#{record}." }

但正在寻找一种使用第一张地图本身实现它的有效方法。

【问题讨论】:

    标签: ruby string loops string-concatenation


    【解决方案1】:

    这可行:

    new_records = records.map{|record| "#{record.name.to_s}." }.sort
    

    你也可以像这样使用+

    new_records = records.map{|record| record.name.to_s + "." }.sort
    

    【讨论】:

    • 我建议您解释一下 ' 和 " 之间的区别以及何时使用它们,因为您已经给出了两种字符串连接类型的示例。
    • @anothermh 随时编辑答案并附上解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2013-04-16
    • 2012-06-20
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多