ruby - 逐行连接两个多行字符串

标签 ruby string concatenation

我有两个多行字符串(代表 ASCII charts )。我想将它们连接起来,以便它们并排。

例如:

s1 = "aaaa
a
aaaa"
s2 = "bbb
bbbb"
puts s1.multi_concat(s2)
#=> aaaa 
#=> a    bbb
#=> aaaa bbbb

如上所示,我希望它们底部对齐。我试过这个:

class String
  def multi_concat(s2)
    lines.map(&:chomp).zip(s2.lines.map(&:chomp)).map(&:join).join("\n")
  end
end

但它存在三个问题:

  • 这两个 block 是顶部对齐的。
  • block 之间没有间距。
  • 短行转移内容:
#=> aaaabbb
#=> abbbb
#=> aaaa

如何“ block 连接”它们?

最佳答案

这是一个强大的多行连接器,它支持:

  • 用于连接两个 block 的任意字符串
  • 顶部、底部和中间对齐
class String
  def multi_concat(str2,options={})
    options[:pad]   ||= ''
    options[:align] ||= :top

    chomped1, chomped2 = [self,str2].map{ |s| s.lines.map(&:chomp) }
    template = "%-#{chomped1.map(&:length).max}s#{options[:pad]}%s"
    delta = chomped2.length - chomped1.length
    unless delta==0
      shorter = delta>0 ? chomped1 : chomped2
      delta = delta.abs
      padding = ['']*delta
      case options[:align]
      when :top    then shorter.concat(padding)
      when :bottom then shorter.unshift(*padding)
      when :middle 
        s1,s2 = *padding.each_cons((delta/2.0).ceil)
        shorter.unshift(*s2)
        shorter.concat(s1)
      end
    end
    chomped1.zip(chomped2).map{ |a| template % a }.join("\n")
  end
end

在行动中:

a = "aaa\naaaa"
b = "bbbb\n\n\nbb"
puts a.multi_concat( b )
#=> aaa bbbb
#=> aaaa
#=>     
#=>     bb

puts a.multi_concat( b, pad:' -> ' )
#=> aaa  -> bbbb
#=> aaaa -> 
#=>      -> 
#=>      -> bb

puts a.multi_concat( b, pad:' ', align: :bottom )
#=>      bbbb
#=>      
#=> aaa  
#=> aaaa bb

puts a.multi_concat( b, pad:' ', align: :middle )
#=>      bbbb
#=> aaa  
#=> aaaa 
#=>      bb

puts b.multi_concat( a, pad:' ' )
#=> bbbb aaa
#=>      aaaa
#=>      
#=> bb   

关于ruby - 逐行连接两个多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37779433/

相关文章:

ruby-on-rails - Rails 使用集合渲染部分内部部分

ruby - 如何从文本文件中读取字符,然后将它们存储到 Ruby 中的散列中

mysql - 在 Rails 项目上运行 ruby​​ 时遇到问题

c - 这两件事有什么区别

MySQL Escape查询结果中的双引号

java - 将字符串合并为结构化字符串

支持 WikiWord 的 ruby​​ markdown 解析器?

java - 如何使用数组用 fillPolygon 替换字符串中的字符

C++如何将字符串 block 写入文件?

Python - 连接 2 个列表