0

I have some code that adds to a session array like so:

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]]

but this produces horrible formatting on my :modalities array. It looks like this:

>> policy_session[:modalities]
>># [["var_1"], "1",[["var_2"], ["2"]], [["var_3"], ["1"]]]

Which is a total pain to try and iterate over later in my program.

I have tried a bunch of different things, but haven't come up with anything that really looks better then this.

How do I create and then add to the array such that my output will be readable? And all formatted the same!

I would like something like this:

>>policy_session[:modalities]
>># [["var_1", "1"], ["var_2", "2"], ["var_3", "1"]]

1 Answer 1

1

Something like this...

policy_session[:modalities] ||= [] # set it to an empty array if nil
policy_session[:modalities] << [params[:modality], policy_session[:mode_list]]

Edit: To get rid of the extra []'s...

policy_session[:modalities] ||= [] # set it to an empty array if nil
policy_session[:modalities] << [params[:modality], policy_session[:mode_list]].flatten
Sign up to request clarification or add additional context in comments.

2 Comments

that's close it produces this for format: [[["var_1"], "1"], [["var_2"], "1"], [["var_3"], "1"]]. Anyway to get rid of those extra brackets around my "var_#"?
thanks worked like a charm, ruby arrays are a little weird coming from working with javascript arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.