0

I have an array

@a = ["a","b","c","d"]

and this is my hash

@a_hash ={"b"=> ["1","2","3"]}

now I want to replace the value of the "b" with @a_hash value into the array.

my expected result is

@a = ["a",["1","2","3"],"c","d"]

How can i get this in ruby?

1
  • Your question is ambiguous because you have told us whether @a is known to contain exactly one element "b" and if not, what is to be done. You can provide an example to clarify your intent but it is not a substitute for a complete and unambiguous statement of the question. Commented May 26, 2017 at 14:53

4 Answers 4

5

Perhaps like this:

a = ["a","b","c","d"]
a_hash ={"b"=> ["1","2","3"]}

a.map! { |x| a_hash[x] || a } 
a #=> ["a",["1","2","3"],"c","d"]
Sign up to request clarification or add additional context in comments.

Comments

3

You can use #fetch method

@a = ["a","b","c","d"]
#=> ["a", "b", "c", "d"]

@a_hash ={"b"=> ["1","2","3"]}
#=> {"b"=>["1", "2", "3"]}

@a.map! { |e| @a_hash.fetch(e, e) }
#=> ["a", ["1", "2", "3"], "c", "d"]

Comments

2

Use Array#index:

@a[@a.index("b")] = @a_hash["b"]
@a
#=> ["a", ["1", "2", "3"], "c", "d"]

It's probably the fastest solution if you have only one occurrence of 'b'. For each occurrence of "b":

@a.map! {|e| @a_hash["b"] if e == "b"}

1 Comment

#1 does not account for the possibility that @a does not have an element "b". I do like the use of index, however, as it terminates as soon as it finds a match (if there is one), unlike the selected answer, which enumerates all elements of @a. Just add a step: i = @a.index("b"); @a[i] = @a_hash["b"] if a (which returns nil if i.nil? #=> true).
0

You can just assign the element to be the value of the hash key:

@a[1] = @a_hash['b']

That's it.

1 Comment

You can simplify: @a = ["a", ["1", "2", "3"], "c", "d"]. :-)

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.