problems with ruby symbols in hash look-up -
i'm trying create simple hash corresponding strings symbols (:student_number, :first_name, ...). i'm having issue retrieving data function though. here's function
snippet a
def get_nice_column_name(col_symbol) column_names = { :first_name => "student's first name", :last_name => "student's last name", :email => "student's email", :given_name => "student's given name" } return column_names[col_symbol] end
here's how use it, not working:
snippet b
col_titles = [] params = {:first_name => 'true', :last_name => 'true', :email => 'true', :given_name => 'true' } params.each |key, value| if ( value == 'true') col_titles << get_nice_column_name(key) end end
when col_titles, expect ["student's first name", "student's last name"], don't anything, [] empty array.
i thought weird tried printing out object_id of symbols (col_symbol in snippet a) , symbols in hash column_names, different object_ids. i'm wondering why different (they both present same symbols). if add function get_nice_column_name in snippet a:
puts "col_symbol " + col_symbol.object_id.to_s + ", while :first_name " + (:first_name).object_id.to_s puts "col_symbol " + col_symbol.object_id.to_s + ", while :last_name " + (:last_name).object_id.to_s puts "col_symbol " + col_symbol.object_id.to_s + ", while :email " + (:email).object_id.to_s puts "col_symbol " + col_symbol.object_id.to_s + ", while :given_name " + (:given_name).object_id.to_s
i in console
col_symbol 98351040, while :first_name 1221688 col_symbol 98351040, while :last_name 580888 col_symbol 98351040, while :email 168888 col_symbol 98351040, while :given_name 1290648
983541040 doesn't match of {1221688, 580888, 168888, 1290648}. why get_nice_column_name useless ? because symbols different under hood?
thanks guys !
regards
if using ruby 1.9 bit more concise way it.
column_names = { :first_name => "student's first name", :last_name => "student's last name", :email => "student's email", :given_name => "student's given name" } params = { :first_name => 'firstname', :last_name => 'lastname', :email => 'email', :given_name => 'givenname' } col_titles = [] col_titles = column_names.values data = params.values_at(*column_names.keys) col_titles # => ["student's first name", "student's last name", "student's email", "student's given name"] data # => ["firstname", "lastname", "email", "givenname"]
this takes advantage of ruby 1.9's new hash behavior, ruby remembers order of insertion , honor order when retrieving keys , values. can similar 1.8, you'd have define order of columns in array, use pull column headings , values of data instead of relying on column_names
set order.
Comments
Post a Comment