else structure in Ruby

I have written something like this, the same if-else logic I knew from Visual Basic 6.0, but I am sure there is a better "Ruby way" of writing it.

Can you please show me how it would look like in Ruby world?

  if params[:medication_name].nil?
    med_name = 'all'
  elsif params[:medication_name] == 'undefined'
    med_name = 'all'
  else
    med_name = params[:medication_name]
  end

For your case, something like this:

med_name = params[:medication_name] 
med_name = 'all' if [nil, 'undefined'].include? med_name

For more general long chains of if / elsif / else , look at case statements. They're overkill in this case, but here's an example:

med_name = case params[:med_name]
   when 'undefined', nil 
     'all'
   else
      params[:med_name]
end

有几种不同的方法可以简化这一点,例如:

med_name = params[:medication_name]
med_name = 'all' if med_name.nil? or med_name == 'undefined'

Ruby独有:

med_name = {nil=>'all', 'undefined'=>'all'}[params[:medication_name]] || params[:medication_name]
链接地址: http://www.djcxy.com/p/25644.html

上一篇: 'case'语句如何与常量一起工作?

下一篇: Ruby中的其他结构