ruby - Returning index with value while using each_with_index method -


constructing basic address book in ruby. have following line of code in program iterates on existing array(@address_book) based on standard numeric input (entrynumber) match array index. resulting value matches index returned. here's code in question:

     puts @address_book.entries.each_with_index.select {|val, i| == (entrynumber - 1)} 

the results great except index returned @ bottom, this: (note 0 @ end of return) i'd ideally index number @ bottom not returned.

view entry number entry number: 1 picked 1 name: adam adams phone number: 111-111-1111 email: aa@aa.com 0 

what missing in terms of returning value, without index?

the problem

the trouble each_with_index turning @address_book.entries array of arrays. here's example of mean:

["a", "b"].each_with_index.to_a # => [["a", 0], ["b", 1]]  

so when apply select each_with_index, selected elements each going array element , index:

["a", "b"].each_with_index.select { |e, i| == 1 } => [["b", 1]]  

a bad fix

you fix using #map select first element of each selected row:

["a", "b"].each_with_index.select { |e, i| == 1 }.map(&:first)  => ["b"]  

using select.with_index

better still, use select.with_index:

["a", "b"].select.with_index { |e, i| == 1}  => ["b"]  

or, in case of code:

@address_book.entries.   each_with_index.select.with_index {|val, i| == (entrynumber - 1)} 

using array#[]

if @address_book.entries array, can index array, not using select @ all:

@address_book_entries[entrynumber - 1] 

if it's not array, can turn 1 #to_a:

@address_book.entries.to_a[entrynumber - 1] 

however, if @address_book.entries large, use lot of memory. careful when turning enumeration array.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -