2011-03-17 107 views
5

所以我正在通過Ruby Koans,我遇到了一個我認爲特定於ruby 1.9.x的問題。我可以在Ruby 1.9.x中使用無參數函數嗎?

def test_calling_global_methods_without_parentheses 

    result = my_global_method 2, 3 
    assert_equal 5, result 
end 

我得到這個:

[email protected]:~/code/ruby_projects/ruby_koans$ rake 
(in /home/james/code/ruby_projects/ruby_koans) 
cd koans 
/home/james/.rvm/rubies/ruby-1.9.2-p180/bin/ruby path_to_enlightenment.rb 
/home/james/code/ruby_projects/ruby_koans/koans/about_methods.rb:21:in `eval': (eval):1: syntax error, unexpected tINTEGER, expecting keyword_do or '{' or '(' (SyntaxError) 
assert_equal 5, my_global_method 2, 3 
           ^
    from /home/james/code/ruby_projects/ruby_koans/koans/about_methods.rb:21:in `test_sometimes_missing_parentheses_are_ambiguous' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:377:in `meditate' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:449:in `block in walk' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:460:in `block (3 levels) in each_step' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:458:in `each' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:458:in `block (2 levels) in each_step' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:457:in `each' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:457:in `each_with_index' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:457:in `block in each_step' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:455:in `catch' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:455:in `each_step' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:448:in `walk' 
    from /home/james/code/ruby_projects/ruby_koans/koans/edgecase.rb:470:in `block in <top (required)>' 
rake aborted! 
Command failed with status (1): [/home/james/.rvm/rubies/ruby-1.9.2-p180/bi...] 
/home/james/code/ruby_projects/ruby_koans/Rakefile:86:in `block in <top (required)>' 
(See full trace by running task with --trace) 
[email protected]:~/code/ruby_projects/ruby_koans$ 

我看了在GitHub上聲稱最近完成了Koans(在過去的2個月)的幾個不同的版本庫,我只是完成看到了我使用的答案(第一段代碼片段)。那麼,這是與我的代碼,我的Ruby安裝或其他東西?

回答

9

您得到的錯誤不是您列出的代碼;它來自它下面的代碼。相關文件的See line 20。該票據說:

注意:我們使用下面的eval因爲示例代碼被認爲是語法上是無效

+3

謝謝!這也是一個提醒,我*真的*需要閱讀更多的錯誤... – jrg 2011-03-18 00:21:15

3

我不知道爲什麼,但是代碼被這樣的評價:

def test_calling_global_methods_without_parentheses 
    assert_equal 5, my_global_method 2, 3 
end 

的問題是,這是ambiguos,可能意味着assert_equal(5, my_global_method(2, 3))assert_equal(5, my_global_method(2), 3)。在這個特定的情況下,你必須使用圓括號。

1

不要忘了刪除方法調用和第一個參數之間的空間。

做這個

eval "assert_equal 5, my_global_method(2,3)"

,而不是

eval "assert_equal 5, my_global_method (2,3)" #beware of the space!

相關問題