jhlu87
jhlu87

Reputation: 4019

rails get output from controller methods?

I have the following code in my Application 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

And I'm inputting an array of strings like this:

 ["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"]

The method get_mkts is supposed to loop through, extract the text up tot the first number and create a unique array of symbols (which is why i used Set). However, I can't get the method to output anything other than the original input. In rails console I'm able to see from the output of "puts m[:mkt]" that each loop through is getting the correct value, I just don't know how to return the set mkts instead of the input value. Any ideas?

Upvotes: 0

Views: 214

Answers (2)

bjhaid
bjhaid

Reputation: 9762

The method can be rewritten has:

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

Looks more rubyish and its shorter and cleaner

Upvotes: 0

mechanicalfish
mechanicalfish

Reputation: 12826

Ruby methods return the result of the last statement if you don't use return. In your case it's each and that's why you get the input back. You can do something like this:

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

This will return the mkts set instead of all_idx.

Upvotes: 2

Related Questions