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

how about this?

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

could you post some expected example output please?

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

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.