[英]Rails 4: Looping through Arrays
I think I am doing something horribly wrong. 我想我做错了什么。 I get this error:
我收到此错误:
TypeError
no implicit conversion of nil into String
if I put this in my View (haml): 如果我将其放在我的视图中(haml):
...
- ["Greg", "is", "cool", "ya"].each do |tag|
.tagwrapper
= link_to tag.to_s.gsub!(/[^0-9A-Za-z]/, ''), '/search?searchtags='+tag.to_s.gsub!(/[^0-9A-Za-z]/, ''), class: 'smaller half-stretched'
...
How am I supposed to do this instead? 我应该怎么做呢?
gsub!
returns nil
if no substitutions were performed. 如果未执行任何替换,则返回
nil
。
Remove !
删除
!
so it becomes: 变成:
= link_to tag.to_s.gsub(/[^0-9A-Za-z]/, ''), '/search?searchtags='+tag.to_s.gsub(/[^0-9A-Za-z]/, ''), class: 'smaller half-stretched'
You should check that gsub!
您应该检查该
gsub!
isn't returning nil
in the event that no substitutions are made: 如果不进行替换, 则不会返回
nil
:
# Will make zero passes
replaced_tag = tag.to_s.gsub!(/[^0-9A-Za-z]/, '')
if replaced_tag
= link_to tag, '/search?searchtags=' + tag, class: 'smaller half-stretched'
Alternatively, in you want to return the string even if no substitutions are made , you can use gsub
(with the !
removed): 或者, 即使不进行任何替换也要返回字符串,则可以使用
gsub
(除去!
):
# Will make four passes, one for each ['Greg', 'is', 'cool', 'ya']
replaced_tag = tag.to_s.gsub(/[^0-9A-Za-z]/, '')
if replaced_tag
= link_to tag, '/search?searchtags=' + tag, class: 'smaller half-stretched'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.