Ruby Ruby 2.3 new feature 之一: 多行字符串更优美的写法

qhwa · 2015年12月23日 · 最后由 wwwicbd 回复于 2017年09月22日 · 8473 次阅读

多行字符串的现状

目前的 ruby ( <= 2.3 preview 1) 中,如果要写一个多行的字符串,是比较麻烦的。

比如

def hello
  puts <<-HEREDOC.
    I know I know
    You will like it.
  HEREDOC
end

hello

输出是

I know I know
You will like it.

前面多了空格!

为了去掉空格,代码就会变得很丑:

def hello
  puts <<-HEREDOC
I know I know
You will like it.
  HEREDOC
end

hello

或者引入 active_support strip_heredoc

总之可以是做到,只是很不方便。

Ruby 2.3 <<~

ruby 2.3 将会引入一个新的语法 <<~ (squiggly heredoc),让你用了就回不去

def hello
  puts <<~HEREDOC
    I know I know
    You will like it.
  HEREDOC
end

hello

完美输出:

I know I know
You will like it.

yeah~

这回强迫症不难受了

终于可以愉快地写 SQL 了

啊,强迫症患者的一剂良药啊

Ruby A PROGRAMMER'S BEST FRIEND

#6 楼 @piecehealth 强迫症表示相当受不了这个“单”引号

之前我是这么写的

def hello
  puts <<-SQL.squlish!
    SELECT *
    FROM users
  SQL
end

squiggly heredoc 哈哈 词典:squiggly adj.弯弯曲曲的

这么赞的功能

人性啊。

我一直这么写

str =<<-EOF.gsub(/^[ ]{4}/, '')
    I know I know
    You will like it.    
        special in this case!

    or in this case 

        content!
EOF

puts str

当然这种只能处理没有 tab 的情况,如果是 tab 和空格的混合情况就比较麻烦了。因为自己平时的编辑器会自动 将 Tab 换成空格所以用这个带处理问题不大

感觉 ruby 是最关心编码体验的编程语言没有之一

虽然我是初学者,看到这个也开生得啊。

完美啊。

python 的"""也有这个问题。。。。。。

问下<< 和 <<- 的区别是什么? 还有下面这个代码的语义能否讲解一下

def print_block(*args)
  puts <<-TEXT % args
-------------------- block %s
  target: %s
   data: '%s' + %s (nonce)
   found: %s

  time:
    took: %f
  verify: %f

  TEXT
end

#19 楼 @lilijreey 区别在于结束的那儿「TEXT」是否要在行首出现。

上面的代码就是「一个大字符串 % args」 % 是 字符串的一个方法

hww Ruby 多行字符串 heredoc 详解 提及了此话题。 08月15日 15:28

第一段代码中 HEREDOC 后面多了一个。

hz_qiuyuanxin 回复

拼写多了个 l , 是 squish!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号