문제

I know that this code may be not quite correct:

def print_string(&str)
puts str
end

print_string{"Abder-Rahman"}

But, when I run it, this is what I get:

#<Proc:0x03e25d98@r.rb:5>

What is this output?

도움이 되었습니까?

해결책

That's the default string representation of a Proc object. Because "Abder-Rahman" is in braces, Ruby thinks you're defining a block. Did you mean to put str.call inside of your function definition? That should call your block and return the string expression you defined inside it.

다른 팁

The problem is that you've declared that the "print_string" method takes a block argument (confusingly named "str") and you simply print the proc itself. You'd probably like to call the given procedure to see the string value it returns:

def call_proc(&proc)
  proc.call
end
call_proc { 'Foobar' }
# => "Foobar"

What you've discovered is the syntax sugar that if you decorate the last argument of a method definition with an ampersand & then it will be bound to the block argument to the method call. An alternative way of accomplishing the same task is as follows:

def call_proc2
  yield if block_given?
end
call_proc2 { 'Example' }
# => 'Example'

Note also that procedures can be handled directly as objects by using Proc objects (or the "lambda" alias for the Proc constructor):

p1 = Proc.new { 'Foo' }
p1.call # => "Foo"
p2 = lambda { 'Bar' }
p2.call # => "Bar"

You're passing a block to the method, as denoted by the & prefix and how you're calling it. That block is then converted into a Proc internally.

puts str.call inside your method would print the string, although why you'd want to define the method this way is another matter.

See Proc: http://www.ruby-doc.org/core/classes/Proc.html

When the last argument of function/method is preceded by the & character, ruby expect a proc object. So that's why puts's output is what it is.

This blog has an article about the unary & operator.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top