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

来源:互联网 发布:微电阻测试仪单片机 编辑:程序博客网 时间:2024/04/28 08:37

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-7890Alice (123) 456-7890Mary-Anne (123) 456-7890Joe (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-7890Alice     (123) 456-7890Mary-Anne (123) 456-7890Joe       (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 }.maxputs rows.map { |row| row[0] = row[0].ljust(pos); row.join }

output:

Fred      (123) 456-7890Alice     (123) 456-7890Mary-Anne (123) 456-7890Joe       (123) 456-7890

0 0
原创粉丝点击