Ruby 教程 在线

1250Ruby 迭代器

Java需要把Map转化成List类型的容器才能使用迭代器,但Ruby有直接针对Map的迭代器:

sum = 0
cutcome = {"block1" => 1000, "book2" => 1000, "book3" => 4000}
cutcome.each{|item, price| sum += price}
print "sum = " + sum.to_s

甚至还可以这样:

sum = 0
cutcome = {"block1" => 1000, "book2" => 1000, "book3" => 4000}
cutcome.each{|pair| sum += pair[1]}
print "sum = " + sum.to_s

1249Ruby 语法

here document 介绍

构建一个 here document 最通用的语法是 << 紧跟一个标识符,从下一行开始是想要引用的文字,然后再在单独的一行用相同的标识符关闭。

puts <<EOF
这是第一行
这是第二行
EOF

执行输出结果为:

这是第一行
这是第二行

更多用法可查看以下实例:

#!/usr/bin/ruby -w
# -*- coding : utf-8 -*-

#(<<)here doucument 感觉本来单行是一个整体变成是一种多行作为一个整体进行导入的方式和 sh 语法相似

print <<EOF
    这是第一种方式创建 here document
    多行字符串。
EOF

print <<"EOF";                # 与上面相同
    这是第二种方式创建here document
    多行字符串。
EOF

print <<`EOC`                 # 执行命令
    ls -al;
    ps -a
EOC

print <<"foo", <<"bar"          # 您可以把它们进行堆叠
    I said foo.
foo
    I said bar.
bar
text =  <<`foo`            # 您可以把它们进行转存
    cat /etc/passwd
foo

puts text

File.open("/home/abc","w") do |io|
    io.write(text)
end
puts "------------------------"
exec "ls -al /home/ && cat /home/abc"