如何在rails函数中创建动态变量?

Mor*_*ker 3 ruby ruby-on-rails dynamic

我有这个代码正在工作:

  case index
   when "Books"
     @reading_img = res.items.first.get_hash('MediumImage')["URL"] # don't show an image
     @reading_link = create_amz_url(search, asin)        

     tempy = @nowreading.content.match(/#nowreading.*/).to_s.gsub("#nowreading",'') # strips away the #nowreading tag
     @nowreading.content = tempy.match(/#{search}.*/).to_s.gsub("#{search}", @reading_link) 
     # replaces the book title (passed in as variable 'search') with the URL'ed title

   when "Music"
     @listening_img = res.items.first.get_hash('MediumImage')["URL"] # don't show an image
     @listening_link = create_amz_url(search, asin)        

     tempy = @nowlistening.content.match(/#nowlistening.*/).to_s.gsub("#nowlistening",'') # strips away the #nowreading tag
     @nowlistening.content = tempy.match(/#{search}.*/).to_s.gsub("#{search}", @listening_link) 
     # replaces the song title (passed in as variable 'search') with the URL'ed title       

   end
Run Code Online (Sandbox Code Playgroud)

我需要为很多很多类别重复这一点.我尝试过这样的东西来干掉代码,但它不起作用:

     def get_img_and_links(act, res, search, asin)
        '@'+act+'ing_img' = res.items.first.get_hash('MediumImage')["URL"] # don't show an image
        '@'+act+'ing_link' = create_amz_url(search, asin)        

        tempy = '@now'+act+'ing'.content.match(/#now"#{act}"ing.*/).to_s.gsub("#now#{act}ing",'') # strips away the #nowreading tag
        '@now'+act+'ing'.content = tempy.match(/#{search}.*/).to_s.gsub("#{search}", '@'+act+'ing_link') 
        # replaces the book title (passed in as variable 'search') with the URL'ed title
     end
Run Code Online (Sandbox Code Playgroud)

本质上,我试图创建一个采取"行为"(例如,"读取","监听"等)的函数,并使该函数内的变量是动态的.这可以实现吗?如果是这样,怎么样?

Ste*_*oss 6

在这里查找instance_variable_set:http://ruby-doc.org/core/classes/Object.html.这是动态创建这些变量所需的.

instance_variable_set "@#{act}ing_img".to_sym, res.items.first.get_hash('MediumImage')["URL"]
Run Code Online (Sandbox Code Playgroud)

等等...