Shortening an if-else structure in Ruby
我写过类似的东西,和我从VisualBasic6.0中知道的if-else逻辑一样,但我确信有更好的"Ruby方法"来编写它。
你能告诉我在红宝石世界里它是什么样子的吗?
1 2 3 4 5 6 7 | if params[:medication_name].nil? med_name = 'all' elsif params[:medication_name] == 'undefined' med_name = 'all' else med_name = params[:medication_name] end |
有几种不同的方法可以简化这一过程,例如:
1 2 | med_name = params[:medication_name] med_name = 'all' if med_name.nil? or med_name == 'undefined' |
对于您的案例,如下所示:
1 2 | med_name = params[:medication_name] med_name = 'all' if [nil, 'undefined'].include? med_name |
更多关于
1 2 3 4 5 6 | med_name = case params[:med_name] when 'undefined', nil 'all' else params[:med_name] end |
露比的独特之处:
1 | med_name = {nil=>'all', 'undefined'=>'all'}[params[:medication_name]] || params[:medication_name] |
使用
1 2 3 4 5 6 7 8 | case params[:medication_name] when nil? med_name = 'all' when 'undefined' med_name = 'all' else med_name = params[:medication_name] end |
另一种方法是对多个值进行测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | foo = true bar = false case when foo == true puts"foo is true" when foo == false puts"foo is false" when bar == true puts"bar is true" when bar == false puts"bar is false" else puts"foo and bar are neither true or false!" end |
您可以执行以下操作:
1 | val = [nil, 'undefined'].include?(params[:medication_name]) ?"all" : params[:medication_name] |