![](/img/trans.png)
[英]Is there a method in Ruby Object to pass itself to a block or proc?
[英]trying to pass control to a Proc from inside a method for irritation but my syntax is wrong in ruby
array = [1, 2, 3]
double = Proc.new { |num| num * 2 }
def custom_each(array)
count = 0
result =[]
while count < array.length
result << yield(array[count]) {&double}
count += 1
end
result
end
p custom_each(array)
**the error:**
/home/ec2-user/environment/ruby/Practise/01_tutorial.rb:9: syntax error, unexpected '{', expecting end
...result << yield(array[count]) {&double}
Process exited with code: 1
有沒有人對如何解決這個問題有任何想法,我的語法錯誤。 我是初學者。
Note: Defining a proc won’t run the code inside it, just like defining a
method won’t run the method, you need to use the call method for that.
如果您希望result
返回[2, 4, 6]
那么您必須執行以下操作
array = [1, 2, 3]
def custom_each(array)
double = Proc.new { |num| num * 2 }
count = 0
result =[]
while count < array.length
result << double.call(array[count])
count += 1
end
result
end
custom_each(array) # [2, 4, 6]
但是要以更多的 ruby 方式完成以上代碼,您應該了解更多關於ruby iterators
、 ruby blocks
、 ruby proc
和array class
首先,您的custom_each
更像map
,因此相應地命名它可能會更好:
def custom_map(array)
count = 0
result =[]
while count < array.length
result << yield(array[count])
count += 1
end
result
end
custom_map([1, 2, 3]) { |num| num * 2 }
#=> [2, 4, 6]
現在, 要將 proc 轉換為 block ,請在調用方法時在它前面加上&
:
double = Proc.new { |num| num * 2 }
custom_map([1, 2, 3], &double)
#=> [2, 4, 6]
這樣,您就可以避免在您的方法中對 proc 進行硬編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.