我正在尝试学习Ruby,并且试图从另一个实例调用一个实例方法。我的代码如下:
class ScanTextInFile
attr_accessor :content , :line_number
def content
@content
end
def line_number
@line_number
end
def content= (text)
@content = text
end
def line_number= (line)
@line_number = line
end
def initialize (content , line_number)
self.content = content
self.line_number = line_number
#self.calculate_word_frequency
end
def calculate_word_frequency
words = self.content.split
words_hash = Hash.new
words.each do | word |
word.downcase!
if words_hash.has_key?
words_hash[key] += 1
else
words_hash[key] = 1
end
highest_wf_count = words_hash.values.max
words_hash.each { |key, value| highest_wf_words.push(key) }
end
end
end
我正在尝试计算单词在给定字符串中出现的次数。我正在calculate_word_frequency
为此使用实例方法。当我注释掉calculate_word_frequency
代码调用正常运行
$ irb -I
irb(main):001:0> require_relative 'test'
=> true
irb(main):002:0>
irb(main):003:0*
irb(main):004:0* a = ScanTextInFile.new("Bla bla foo foo bar baz foo bar bar", 1)
=> #<ScanTextInFile:0x007fc7a39b01c8 @content="Bla bla foo foo bar baz foo bar bar", @line_number=1>
但是,当我calculate_word_frequency
在代码initialize
块中调用实例方法时,出现错误消息ArgumentError: wrong number of arguments (0 for 1)
$ irb -I
irb(main):001:0> require_relative 'test'
=> true
irb(main):002:0> a = ScanTextInFile.new("Bla bla foo foo bar baz foo bar bar", 1)
ArgumentError: wrong number of arguments (0 for 1)
我尝试self
在调用方法的同时删除该操作,但仍然出现错误。调用该方法时,我不知道出了什么问题。正确的方法是什么?
该错误在这里非常具有描述性,在第32行中您具有以下内容:
if words_hash.has_key?
该方法Hash#has_key?
要求您传入一个参数,如some_hash.has_key?("a_key")
我认为您的意思是这样使用:words_hash.has_key?(word)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句