Hit9 Blog Wiki Project Links Archives
Page: First UP Pre Next Back

ruby学习笔记(简明教程)

Fork me on GitHub

允许转载, 但转载请注明出处

1.打印字符串

三种打印方式:

irb(main):001:0> p 'hello'
"hello"
=> "hello"
irb(main):002:0> puts 'hello'
hello
=> nil
irb(main):003:0> print 'hello'
hello=> nil

会发现print打印不带换行,puts和p打印带换行(print "hello\n"实现换行)

另外会发现p打印返回打印的字符串,print和puts返回nil

2.heredoc

语法:

<<结束标志
# here docs
结束标志

sample:

print <<EOF  # heredoc
hello
world
EOF

print <<'EOF' # 同上
hello
world
EOF

print <<`EOF` # 执行外部命令
echo 'hello world'
EOF

print <<"foo", <<"bar"  # 你可以把这些heredoc堆积起来
    I said foo.
foo
    I said bar.
bar

输出

hello
world
hello
world
hello world
        I said foo.
        I said bar.

3.BEGIN和END

BEGIN:声明将在程序的开始调用的代码

END:声明将在程序的最后调用的代码

print 'hello world'
BEGIN{
  print 'begin code'
}
END{
  print 'end code'
}

4.程序注释

单行注释:

# comments

多行注释:

=begin
# comments
# comments
# comments
=end

Support:mkdwiki