您的位置:首页 > 编程语言 > Ruby

Does Ruby have a method similar to Emacs align-regexp?

2014-09-05 10:43 239 查看
Looking for a Ruby method to operate on an array of strings and align them according to a regex given as as an argument. Emacs has a defun called align-regexp that does this interactively when operating on a region of a buffer.

Here is a portion of the emacs doc string for align-regexp.

For example, let's say you had a list of phone numbers, and wanted to align them so that the opening parentheses would line up:
Fred (123) 456-7890
Alice (123) 456-7890
Mary-Anne (123) 456-7890
Joe (123) 456-7890


There is no predefined rule to handle this, but you could easily do it using a REGEXP like "(". All you would have to do is to mark the region, call `align-regexp' and type in that regular expression. Here is the result:
Fred      (123) 456-7890
Alice     (123) 456-7890
Mary-Anne (123) 456-7890
Joe       (123) 456-7890

lines = [
'Fred (123) 456-7890',
'Alice (123) 456-7890',
'Mary-Anne (123) 456-7890',
'Joe (123) 456-7890',
]
rows = lines.map { |line| line.partition('(') }
pos = rows.map { |row| row[0].size }.max
puts rows.map { |row| row[0] = row[0].ljust(pos); row.join }
output:
Fred      (123) 456-7890
Alice     (123) 456-7890
Mary-Anne (123) 456-7890
Joe       (123) 456-7890
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐