Ruby 怎么传入一个函数和它的参数

yakczh · 2013年08月12日 · 最后由 coderek 回复于 2013年08月13日 · 2635 次阅读
def linkhandle(urls,prefix)
    arr=[]
    for url in urls
     arr.push(prefix+url)
end
  reuturn arr
end

def process(handle,prefix="https://")
    urls=['./201207/t20120705_1887040.html', './201206/t20120608_1846662.html']
  links = handle(urls,prefix);
    return links; 
end 
     list= process(linkhandle,'http://www.baidu.com')
 print list.join("\n")

如何才能在 process 中传入一个处理链接的函数,根据传入不同的域名得到相应的链接

将函数以 block 的形式传递进去,然后在 process 方法中用 yeild 来调用?是这个意思?

a = Proc.new { |urls, prefix| arr = []; urls.each{|url| arr.push(prefix + url)}; arr}

def process(handle, prefix="https://") urls=['./201207/t20120705_1887040.html', './201206/t20120608_1846662.html'] links = handle.call(urls, prefix) links end

list = process(a, 'http://www.baidu.com') print list.join("\n")

这意思? 没仔细推敲

呵呵,不知道你是不是想这样:

def linkhandle(urls,prefix)
  urls.map { |url| "#{prefix}#{url}" }
end

def process(handle,prefix="https://")
  urls=['./201207/t20120705_1887040.html', './201206/t20120608_1846662.html']
  send handle, urls, prefix
end 

list= process(:linkhandle,'http://www.baidu.com')
print list.join("\n")

:linkhandle 这种用法叫什么?

@small_fish__ 这样对吧?

def process prefix
  urls = ['./201207/t20120705_1887040.html', './201206/t20120608_1846662.html']
  yield urls, prefix
end

linkhandle = Proc.new {|urls, prefix| urls.map{|u| "#{prefix}/#{u}"}}
print process('http://www.baidu.com', &linkhandle).join("\n")
需要 登录 后方可回复, 如果你还没有账号请 注册新账号