ruby-on-rails – 如何在rails函数中创建动态变量?
发布时间:2020-12-17 01:45:12 所属栏目:百科 来源:网络整理
导读:我有这个代码正在工作: 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("#n
我有这个代码正在工作:
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 我需要为很多很多类别重复这一点.我尝试过这样的东西来干掉代码,但它不起作用: 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 本质上,我试图创建一个采取“行为”(例如,“阅读”,“收听”等)的函数,并使该函数内的变量是动态的.这可以实现吗?如果是这样,怎么样? 解决方法
在这里查找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"] 等等… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |