如何在另一个定义

时间:2015-11-13 22:08:17

标签: ruby

@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

当尝试在longest_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,忽略第二个功能的功能,我还没有制作那个功能,只是发布了例如。

1 个答案:

答案 0 :(得分: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