Viral
Viral

Reputation: 320

Java ArrayList in Ruby

When I submit the form to server, Rails.logger.info params gives

{"cgAttr"=>{"1"=>"abc,pqr", "2"=>"US"}}

and I want

{"cgAttr"=>{"1"=>"abc", "1" => "pqr", "2"=>"US"}}

PS. "1" is input text box in UI that take multiple comma-separate values ("abc,pqr") and on server I am converting that entire string into array (["abc", "pqr"]).

Can Any one point me in correct direction?

Basically, I want to create ArrayList similar to Java in my Ruby on Rails application. Does anyone know how to achieve it. (I have not tried JRuby plugin yet)

Upvotes: 0

Views: 3235

Answers (3)

steenslag
steenslag

Reputation: 80085

It can be done:

h = {}
h.compare_by_identity
a = "1"
b = "1"
h[a] = "abc"
h[b] = "pqr"
p h # {"1"=>"abc", "1"=>"pqr"}

but it doesn't feel right.

Upvotes: 0

bkempner
bkempner

Reputation: 652

Can't be done, hash key must be a unique value:

{:foo => 'foo1', :foo => 'foo2'} #=> {:foo => 'foo2'}

Think about it, how would you differentiate between the two elements? my_hash[:foo] can only refer to one element, but if two elements have the same :foo key how can you distinguish between the two?

I like Dave Newtons answer, because then you can actually access them, e.g.:

my_hash[:foo][0], my_hash[:foo][1]

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160271

The easiest answer is to use split:

arr = params[:cgAttr]["1"].split(",")

(Also not psyched about using "1" as a parameter name.)

Upvotes: 1

Related Questions