Ruby Learn ruby the hard way 第六节 问题

guaishushu · 2012年04月29日 · 最后由 disco26 回复于 2013年04月09日 · 2812 次阅读

有一个代码这样写 x = "There are #{10} types of people." 10 为什么要加 #{}呢

不解。bypass 吧。

这里估计是要说明数字也可以放入#{}里面吧。

根据 在 ruby 中,一切都是对象 ,下面两个没有多大的区别吧。只是第一个比较间接而已。

num = 10
x = "There are #{num} types of people."

x = "There are #{10} types of people."

喔 后面有一段这样的代码 hilarious = false joke_evaluation = "Isn't that joke so funny?! #{hilarious}" 是不是作者想表达在#{}中 都会被转化为字符串?

匿名 #5 2012年04月29日

#4 楼 @guaishushu hilarious 是个变量,在这两行代码间可以对这个变量更改,比如可以加点 IO 什么的来对这个判断。我觉得这只是作者的编码习惯而已

把一个对象放到#{},会调用其to_s,Fixnum 的实例数字 10 也不例外。

zed shaw 十分 geek,有的东西说的估计比较拐

各位好,

我在 Learn Ruby The Hard Way 的第 18 個練習裡有一些小疑問想請教

http://ruby.learncodethehardway.org/book/ex18.html

this one is like your scripts with argv

def puts_two(*args) arg1, arg2 = args puts "arg1: #{arg1}, arg2: #{arg2}" end

ok, that *args is actually pointless, we can just do this

def puts_two_again(arg1, arg2) puts "arg1: #{arg1}, arg2: #{arg2}" end

作者說 *args 其實是 pointless, 但是程式仍然可以執行? 那*args 的意義到底是?

因為我如果把args 換成任意的____ , 比如說:

def puts_two(*a) arg1, arg2 = a puts "arg1: #{arg1}, arg2: #{arg2}" end

程式也都能執行,還是說*號有特別的意義?

小弟是新手,沒有程式底子,請各位多指教

謝謝解惑!

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