English 中文(简体)
替代方式是确定物体是否列入清单?
原标题:Ruby - alternative style for determining if object is contained within a list?
  • 时间:2012-04-30 18:29:32
  •  标签:
  • ruby

让我说,你有多种权利,例如,条件。

if action ==  new  || action ==  edit  || action ==  update 

另一种写法是:

if [ new ,  edit ,  action ].include?(action)

但是,这感觉到的是,这种逻辑的写法是倒退的。

是否有任何内在方式做这样的事情:

if action.equals_any_of?( new ,  edit ,  action )

?

更新——我非常热衷于这一微薄的幻灯:

class Object
  def is_included_in?(a)
    a.include?(self)
  end
end

最新情况 2 - 根据以下评论作出的改进:

class Object
  def in?(*obj)
    obj.flatten.include?(self)
  end
end
最佳回答

使用reg?

action =~ /new|edit|action/

或:

action.match /new|edit|action/

或者仅仅写出一种简单的实用方法,在你看来,这种方法具有内在的意义。

问题回答

另一种办法是:

case action
when  new ,  edit ,  action 
  #whatever
end

您也可以对类似案件定期发表看法。

if action =~ /new|edit|action/

您可使用<条码>%w在座标的阵列上:

%w(new edit action).include? action




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签