我有一些代码添加到会话数组中,如下所示:
if policy_session[:modalities] #array exists just add new value to it
policy_session[:modalities] << [params[:modality], policy_session[:mode_list]]
else #the array does't exist yet, so create and add first one.
policy_session[:modalities] = [params[:modality], policy_session[:mode_list]]
但这会在我的:modalities
数组上产生可怕的格式。它看起来像这样:
>> policy_session[:modalities]
>># [["var_1"], "1",[["var_2"], ["2"]], [["var_3"], ["1"]]]
在我的程序中稍后尝试迭代这是一种痛苦。
我尝试了很多不同的东西,但还没有想出任何真正看起来更好的东西。
如何创建然后添加到数组中以使我的输出可读?所有格式都一样!
我想要这样的事情:
>>policy_session[:modalities]
>># [["var_1", "1"], ["var_2", "2"], ["var_3", "1"]]
答案 0 :(得分:1)
像这样......
policy_session[:modalities] ||= [] # set it to an empty array if nil
policy_session[:modalities] << [params[:modality], policy_session[:mode_list]]
编辑:摆脱额外[]的......
policy_session[:modalities] ||= [] # set it to an empty array if nil
policy_session[:modalities] << [params[:modality], policy_session[:mode_list]].flatten