1 . 3.times { puts "hello" } 在ruby内部实现方式
核心:利用yield 实现回调
例子代码:
ruby 代码
- def takeBlock(p)
- if block_given?
- yield(p)
- else
- puts p
- end
- end
- takeBlock "a"
- takeBlock("a") {|x| puts "++++++++++" + x}
2. 类方法不能被实例变量调用
ruby 代码
- class Test
- def self.test1
- puts "test1"
- end
- end
- Test.test1
- test1 = Test.new
- test1.test1 #这样调用就是错误的
3. 文件操作
ruby 代码
- #w会重写
- File.open("somefile","w") do |file|
- file.puts "Line 1"
- file.puts "Line 2"
- file.puts "Third and final line"
- end
- 或者
- #打开一个操作文件的句柄
- file = File.open("somefile","w")
- file.puts("aaaa");
- file.puts("bbbb");