preloader
學習

以精簡形式傳出Ruby function的多項回傳值

Ruby Array資料結構容許,一個 Array 同時裝載多項型態的元素(element),element 可以是 Integer, String, Hash……等等。這項特性可以用在 精簡地傳入多項參數 ,也可用在傳出多項回傳值,舉例如下:

套用前面文章「以精簡方式傳入多項參數」的例子,修改例子,變成

def method_1( dataStructure_1, dataStructure_2, array_flag_operation )

  flag_operation_1 = array_flag_operation[0] # flag_operation_1 can be an object type of string or integer, float.

  flag_operation_2 = array_flag_operation[1] # flag_operation_2 can be an object type of string or integer, float.

  flag_operation_3 = array_flag_operation[2] # flag_operation_3 can be an object type of string or integer, float.

  flag_operation_4 = array_flag_operation[3] # flag_operation_4 can be an object type of string or integer, float.

.

.

. # (produce new Objects: modify_dataStructure_1 and modify_dataStructure_2)

.

# want to return modify_dataStructure_1 and modify_dataStructure_2

return modify_dataStructure_1, modify_dataStructure_2

end

 

上面這個例子,無法如作者所想,回傳多個回傳值,而且會有編譯錯誤,因為 Ruby function的 return 只能回傳一個變數。

 

修改上面的例子如下:

def method_1( dataStructure_1, dataStructure_2, array_flag_operation )

  flag_operation_1 = array_flag_operation[0] # flag_operation_1 can be an object type of string or integer, float.

  flag_operation_2 = array_flag_operation[1] # flag_operation_2 can be an object type of string or integer, float.

  flag_operation_3 = array_flag_operation[2] # flag_operation_3 can be an object type of string or integer, float.

  flag_operation_4 = array_flag_operation[3] # flag_operation_4 can be an object type of string or integer, float.

.

.

. # (produce new Objects: modify_dataStructure_1 and modify_dataStructure_2)

.

  # want to return modify_dataStructure_1 and modify_dataStructure_2

  array_many_return_Value = Array.new

  array_many_return_Value[0] = modify_dataStructure_1

  array_many_return_Value[1] = modify_dataStructure_2

  return array_many_return_Value

end

 

caller 或 main procedure 呼叫 callee method_1 的寫法應寫成如下:

array_returnValue_collection = method_1(dataStructure_1, dataStructure_2, array_many_flags_collection)

new_modify_dataStructure_1 = array_returnValue_collection[0]

new_modify_dataStructure_2 = array_returnValue_collection[1] 

 

這樣即可完成回傳多項回傳值