LRTHW练习八

正确代码:

formatter = "% {first} % {second} % {third} % {fourth}"

puts formatter % {first: 1, second: 2,third: 3,fourth: 4}
puts formatter % {first: "one", second: "two", third: "three", fourth: "four"}
puts formatter % {first: true, second: false, third: true, fourth: false}
puts formatter % {first: formatter,second: formatter, third: formatter, fourth: formatter}
puts formatter % {
    first: "I had this things" ,
    second: "That you could type uo right.",
    third: "But it didn't sing ." ,
    fourth: "So I said goodnight."
}

显示正确的结果:

[ufindme@ufindme rubywork]$ ruby ex8.rb 
1 2 3 4
one two three four
true false true false
% {first} % {second} % {third} % {fourth} % {first} % {second} % {third} % {fourth} % {first} % {second} % {third} % {fourth} % {first} % {second} % {third} % {fourth}
I had this things That you could type uo right. But it didn't sing . So I said goodnight.

过程错误:

ex8.rb:3:in `%': key{first} not found (KeyError)
    from ex8.rb:3:in `<main>'

one two three four
ex8.rb:5:in `%': key{first} not found (KeyError)
    from ex8.rb:5:in `<main>'
提示说是:在使用formatter格式字符串时,没有找到其中的first标签,是Key的问题。

  然后检查第一行输出中,first标签是否写对。

 

扩展:将原来的最后一个输出的双引号换成单引号

代码

formatter = "% {first} % {second} % {third} % {fourth}"

puts formatter % {
    first: 'I had this things',
    second: 'That you could type uo right.',
    third: "But it didn't sing ." ,
    fourth: 'So I said goodnight.'
}

结果:

[ufindme@ufindme rubywork]$ ruby ex8-2.rb 
I had this things That you could type uo right. But it didn't sing . So I said goodnight.

曾有错误提示:

  ex8-2.rb:6: syntax error, unexpected tIDENTIFIER, expecting '}'
      third: "But it didn"t sing ." ,
                         ^
  ex8-2.rb:6: syntax error, unexpected tSTRING_BEG, expecting '('
      third: "But it didn"t sing ." ,
                                 ^
  ex8-2.rb:7: syntax error, unexpected tCONSTANT, expecting end-of-input
      fourth: "So I said goodnight."

错误的原因是:在双引号“”里面放了个双引号,是的后面那个双引号单独出现报错

 

后面将第一行的双引号改成单引号 后,还是可以正常显示,显示一样的结果。

 

posted @ 2014-09-02 15:28  SchrodingerCat  阅读(213)  评论(0编辑  收藏  举报