Ruby 求解 Ruby 中的%s 怎么使用?

lissdy · 2016年07月25日 · 最后由 heliang7 回复于 2016年07月27日 · 3835 次阅读

在 codewars 上看到这样一道题目:

You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples: likes [] // must be "no one likes this" likes ["Peter"] // must be "Peter likes this" likes ["Jacob", "Alex"] // must be "Jacob and Alex like this" likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this" likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"

题目本身没什么难度,但是看到有一个实现是这样的:

def likes(names)
  case names.length
  when 0
    "no one likes this"
  when 1
    "%s likes this" % names
  when 2
    "%s and %s like this" % names
  when 3
    "%s, %s and %s like this" % names
  else
    "%s, %s and %d others like this" %
      [names[0], names[1], names.length - 2]
  end
end

麻烦问下大神这里的%s和%是怎么用的,从来没有接触过这样的写法。。。

这种用的比较少,其实 Python 也有同样的语法,就是传统的 C 风格的字符串啦,比如 C 语言的 printf,Jaba 的 String.format,字符串模板的语法是完全一致的,这种写法有个好处,比方说格式化小数保留两位可以写成 "%.2f" % 1.1111 # => "1.11"

#1 楼 @jasl 印象中 java 也有这样的占位写法,不过在 ruby 中确实第一次看到^_^

这个没记错是来自于 C 的吧

格式化输出吧,C 的东西。之前在社区谁贴了网站,给你 10 个方法,让判断是 ruby 的还是 rails 的里遇到过。

#1 楼 @jasl java 吧,表示没用过这种用法

应该和 java 中 String 类的 format(),C 语言的 sprintf() 方法类似,格式化字符串。

#3 楼 @lissdy 这个语法 Python 是有的 这种风格,应该来自 C 的,sprintf printf scanf 等等嘛,Java 没有这种语法 但是 String.format 效果是一样的

#9 楼 @jasl #8 楼 @nouse 明白咯,感谢 Y(^_^)Y

#7 楼 @uudui 利利说的对

#6 楼 @easonlovewan 这种风格写起来不太方便连接后续的语句,所以用的很少,而且楼上也有人提了 Ruby 也有 sprintf,两者效果是等价的 这种格式化字符串的好处是类似显示价格要取两位小数啊,很方便 "%.2f" 即可

这好像是 C 语言的格式化输出功能,见http://www.cplusplus.com/reference/cstdio/sprintf/ 。%s代表一个字符,%d代表一个整数。

写了三年代码,这都不知道啊

15 楼 已删除
17 楼 已删除
18 楼 已删除
19 楼 已删除
需要 登录 后方可回复, 如果你还没有账号请 注册新账号