rails从控制器方法获得输出?

时间:2013-12-12 20:47:28

标签: ruby-on-rails methods controller

我的应用程序控制器中有以下代码

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def get_mkts(all_idx)
    mkts = Set.new
    all_idx.each do |idx|
      m = decode_index_names(idx) 
      puts m[:mkt]
      mkts.add(m[:mkt])
    end
  end


  def decode_index_names(name)
      mkt = name.split(/[0-9]/)[0]
      type = get_first_num(mkt);
      {:mkt => mkt,:type => type}
  end

  def get_first_num(str)
    str[/\d+/]
  end
end

我正在输入这样的字符串数组:

 ["USEQUITIES2tv10", "USEQUITIES2tv15", "USEQUITIES2tv20", "NONUSEQUITIES2tv5", "NONUSEQUITIES2tv10", "NONUSEQUITIES2tv15", "NONUSEQUITIES2tv20", "BONDS2tv5", "BONDS2tv10", "BONDS2tv15", "BONDS2tv20"
, "ES1", "ES2tv5", "ES2tv10", "ES2tv15", "ES2tv20", "NQ1", "NQ2tv5", "NQ2tv10", "NQ2tv15", "USBONDS2tv5", "USBONDS2tv10", "USBONDS2tv15", "USBONDS2tv20", "GERMANBONDS2tv5", "GERMANBONDS2tv10", "GERMANB
ONDS2tv15", "GERMANBONDS2tv20", "EQUITIESnBONDS2tv5", "EQUITIESnBONDS2tv10", "EQUITIESnBONDS2tv15", "EQUITIESnBONDS2tv20", "COMMODITIES2tv5", "COMMODITIES2tv10", "COMMODITIES2tv15", "COMMODITIES2tv20",
 "CURRENCIES2tv5"]

方法get_mkts应循环,将文本提取到第一个数字并创建一个唯一的符号数组(这就是我使用Set的原因)。但是,我不能让方法输出除原始输入之外的任何内容。在rails控制台中,我能够从“puts m [:mkt]”的输出中看到每个循环都得到正确的值,我只是不知道如何返回设置mkts而不是输入值。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

如果不使用return,Ruby方法将返回最后一个语句的结果。在你的情况下它是each,这就是你得到输入的原因。你可以这样做:

def get_mkts(all_idx)
  mkts = Set.new
  all_idx.each do |idx|
    m = decode_index_names(idx) 
    puts m[:mkt]
    mkts.add(m[:mkt])
  end
  mkts
end

这将返回mkts集而不是all_idx

答案 1 :(得分:0)

该方法可以重写:

def get_mkts(all_idx)
  all_idx.map { |idx| decode_index_names(idx) }.uniq
end

看起来更红宝石,更短更清洁