0

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)

2
  • JRuby is not a "plugin", it is a complete implementation of the Ruby language. Commented Nov 29, 2011 at 23:42
  • Ruby hash indexes MUST be unique. You are asking for the hash to have two "1" indexes, which isn't possible. Commented Nov 29, 2011 at 23:42

3 Answers 3

1

The easiest answer is to use split:

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

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

Sign up to request clarification or add additional context in comments.

10 Comments

if I do that than it gives "1"=>["abc", "pqr"]. Is there a way I can achieve {"cgAttr"=>{"1"=>"abc", "1" => "pqr", "2"=>"US"}}
@Viral No, it's a hash. It's not really clear what you're actually trying to do; are you sending something to a Java server? You could use array notation and say { "foo[0]" => "abc", "foo[1]" => "pqr" }. Otherwise you're going to need to be more specific. My code snippet is on the rails side and cannot produce what you're saying, because I'm consuming parameters.
yeah dave, thanks for guidance..I am actually send values to Java API but the API accept values in this cgAttr = [{name: "abc", loc: "us"}, {name:"pqr", loc:"us"}]. Do you think creating my own hash map will help me?
@Viral That's a completely different structure; that's an array of hashes. Sure, creating that from the form data would be trivial.
ok got it...I was trying to explore more options to match that data structure...not sure if I use JRuby that will help me or not.
|
0

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]

1 Comment

yeah that make more sense...will check any other alternatives
0

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.

Comments

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.