2015-11-13 99 views
0
@songs = [{artist: 'Artist', title: 'Title String', playback: '04:30'} etc] 

def convert_to_secs 
    a = str.split(':').map!{|x| x.to_i} 
    return (a[0] * 60) + a[1] 
end 

def longest_possible(playback) 
    @songs.select do |hsh| 
     x = hsh[:playback].convert_to_secs 
    end 
    return x 
end 

内当试图调用内部lo​​ngest_possible convert_to_seconds我得到以下错误:如何调用一个方法定义的另一个定义

longest_possible.rb:5:in `block in longest_possible': private method 
`convert_to_secs' called for "04:30":String (NoMethodError) 
from longest_possible.rb:4:in `select' 
from longest_possible.rb:4:in `longest_possible' 
from longest_possible.rb:15:in `<main>' 

我不知道如果我的问题可以用范围运营商来解决,或者这是否需要与课程相关的东西(而不是我已经涉及到的东西)。请您指出我正确的方向吗? PS,忽略第二个函数的功能,我还没有开始做,但只是张贴例如。

+0

尝试改变你的方法到'def convert_to_secs(a)'和调用'x = convert_to_secs(hsh [:playback])''。 –

回答

0

主要问题似乎是您使用字符串作为接收者调用方法。然后尝试在为字符串预定义的方法中找到方法convert_to_secs,但找不到它。相反,你应该通过hsh [:playback]作为参数。所以你的代码应该是这样的:

def convert_to_secs(str) # Note the argument str introduced here 
    # You don't need map! here. Normal map suffices. 
    a = str.split(':').map {|x| x.to_i} 
    # In Ruby, you can leave away the return keyword at the end of methods. 
    (a[0] * 60) + a[1] 
end 

def longest_possible(playback) 
    @songs.select do |hsh| 
    x = convert_to_secs(hsh[:playback]) 
    end 
    return x 
end 
相关问题