簡體   English   中英

如果紅寶石條件更好的書寫方式

[英]Better way to write if condition in ruby

if args.size == 5
  value_for,alt_currency_id,amount,exchange_rate_code,tran_dt = args
else
  value_for,alt_currency_id,amount,exchange_rate_code,year_no,period_no = args
end

有什么更好的方法可以寫這種條件?

我只是完全跳過該條件。 如果您沒有第五個參數, period_no將只是nil

如果需要將period_no設置為某些默認值,則可以執行以下操作:

period_no ||= sane_default

為了嚴格滿足您的要求,我會這樣做:

value_for, alt_currency_id, amount, exchange_rate_code = args.shift(4)
tran_dt, year_no, period_no = [nil, nil, nil] # or some sensible defaults
case args.size
when 1 then tran_dt = args.shift
when 2 then year_no, period_no = args.shift(2)
end

但是這段代碼有它的味道。 我將看看重新設計該方法的調用方式。

絕對是一種代碼味道,特別是因為變量稱為args 如果將所有這些參數作為可選值傳遞,則最好的方法是將變量參數設置為哈希值。

def whatever(value_for, alt_currency_id, amount, options = {})
  tran_dt = options[:tran_dt]
  year_no = options[:year_no]
  period_no = options[:period_no]
  ...
end

也許默認情況下將period_no分配為nil ,並使用它來確定要使用的參數集:

def process_record(value_for, alt_currency_id, amount, exchange_rate_code, tran_dt, period_no=nil)
  year_no = period_no ? tran_dt : nil
  puts "tran_dt: #{tran_dt.inspect}"
  puts "year_no: #{year_no.inspect}"
  puts "period_no: #{period_no.inspect}"
end

process_record(:foo, :bar, :baz, :buz, Time.now)
# Output:
#
# tran_dt: Mon Sep 13 15:52:54 -0400 2010
# year_no: nil
# period_no: nil

process_record(:foo, :bar, :baz, :buz, 2010, 1)
# Output:
#
# tran_dt: 2010
# year_no: 2010
# period_no: 1

這是一種稍微干燥代碼的方法:

value_for, alt_currency_id, amount, exchange_rate_code, year_no, period_no = args
if period_no.nil?
  tran_dt = year_no
  year_no = nil # May or may not be needed, depending on later code
end

我也知道Ruby還有兩個三元運算符

a = true  ? 'a' : 'b' #=> "a"  
b = false ? 'a' : 'b' #=> "b"

要么

a = (true  && 'a') || b #=> "a"  
b = (false && 'a') || b #=> "b"

您正在處理命令行嗎? 照原樣放置,對我而言,乍一看最容易理解:)否則它可能會散發出淡淡的味道。 您只需看一下5個參數所需的設置,否則。 如果這些不是命令行參數,我建議引入哈希。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM