Yuan Yijun (bbbush) wrote,
Yuan Yijun
bbbush

试用 RubyMine


# lib/class1.rb
class Class1

  def construct_strings
    yield "Hello,"
    yield "World!"
  end

  def put_strings2(*x)
    x.each {|i|
      print i
      print " "}
    $stdout.flush
  end

  def put_strings(x)
    print x
    print " "
    $stdout.flush
  end

end

# test/class1-test.rb
require("../lib/class1")

h = Class1.new
h.construct_strings {|x| h.put_strings2(x)}
proc2 = Proc.new{|x| h.put_strings2(x)}
h.construct_strings &proc2
puts

h.construct_strings {|x| h.put_strings(x)}
proc = Proc.new{|x| h.put_strings(x)}
h.construct_strings &proc


Conclusion: 没有基础,一时半会儿搞不明白。need help:
1. 不安装 Ruby SDK 时就提示找不到 puts 之类的 symbol;装好了就有无数的 "no blocks given (yield)  (LocalJumpError)" 异常。
2. 我的本意是想写一个函数 put_strings,接受 construct_strings 作为参数,在函数里执行 construct_strings 然后输出,应该怎么做?
3. 我想不通为什么在 construct_strings 的 block 里,|x| 既可以是 string 又可以是 array

edit: for block vs. object (proc or lambda) http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
as Ruby is fully object-oriented, this can be handled quite cleanly by saving reusable code as an object itself. This reusable code is called a Proc (short for procedure). The only difference between blocks and Procs is that a block is a Proc that cannot be saved, and as such, is a one time use solution

# lib/class1-put_strings3.rb
class Class1

  def construct_strings_f(proc)
    construct_strings &proc
  end

  def put_strings3(env)
    env.call(->(x){put_strings(x)})
  end

end

# test/class1-put_strings3-test.rb
require("../lib/class1")
require("../lib/class1-put_strings3")

h = Class1.new

cons = Proc.new{|p| h.construct_strings &p}
h.put_strings3(cons)

cons2 = Proc.new{|p| h.construct_strings_f p}
h.put_strings3(cons2)

h.put_strings3(lambda {|p| h.construct_strings &p})

h.put_strings3(lambda {|p| h.construct_strings_f p})

h.put_strings3(->(p){h.construct_strings &p})

# and the "method" method
h.put_strings3(h.method("construct_strings_f"))
h.put_strings3(h.method(:construct_strings_f))


edit: for question #3, http://www.skorks.com/2009/08/method-arguments-in-ruby/
(Optional Arguments)..if no arguments are supplied, then p will be an empty array, otherwise, it will be an array that contains the values of all the arguments that were passed in...obviously, it makes no sense to have two optional arguments in an argument list (i.e. two parameters with * notation)
Tags: reading, 小东西
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments