0

Given an array

array = ['a','b','c','d','e','f']

and a hash

hash = {"a"=>1,"b"=>2,"c"=>3,"d"=>4,"e"=>5,"f"=>6}

I would like to create a new array which contains the objects corresponding to the value of every index from the third onward. I am currently doing it like this:

newArray = []
array[2..-1].each do |item|
  newArray << hash[item]
end

I feel like this could be done in one line (possibly without creating the newArray beforehand as I would like to put this directly into another object's initialization code). Is this possible?

1
  • If you want to do it one line, just remove the linebreaks. In Ruby, you can always remove all linebreaks in all programs, by either replacing them with semicolons, keywords, or sometimes even nothing. In your case: newArray = []; array[2..-1].each do |item| newArray << hash[item] end Voilà: one line. Commented Apr 12, 2016 at 0:36

4 Answers 4

3

You want to use Hash#values_at

hash.values_at *array[2..-1]
# => [3, 4, 5, 6]
Sign up to request clarification or add additional context in comments.

Comments

1

how about this?

array[2..-1].map{|x| hash[x]}

could you post some expected example output please?

Comments

0
hash.keep_if {|k,v| array.slice(2, array.length-2).index(k) }.values

or

hash.dup.keep_if {|k,v| array.slice(2, array.length-2).index(k) }.values

if you need to maintain the original hash values

Comments

0
array[2..-1].inject([]) {|ary, x| ary << hash[x]}

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.