ruby - How to merge values of a single hash? -


is there way merge values of single hash?

example:

address = {      "apartment" => "1",     "building" => "lido house",     "house_number" => "20",     "street_name" => "mount park road",     "city" => "greenfield",     "county" => nil,     "post_code" => "wd1 8dc" } 

could outcome looks this?

1 lido house, 20 mount park road, greenfield, wd1 8dc 

address.compact remove value equals nil, if in method include string interpolation , want exclude nil value addresses , include others without comma @ end?

def address(hash)     hash.compact     puts "#{hash["apartment"]} #{hash["building"]}, \n#{hash["house_number"]} #{hash["street_name"]}, \n#{hash["city"]}, \n#{hash["county"]}, \n#{hash["post_code"]}" end 

you need join values in string:

"#{address['house_number']} #{address['street_name']},\n#{address['city']},\n#{address['post_code']}" 

you improve formatting making helper method, , using heredoc:

def formatted_address(address)   <<~address     #{address['house_number']} #{address['street_name']},     #{address['city']},     #{address['post_code']}   address end 

usage:

address = {    "house_number" => 20,   "street_name" => "mount park road",   "city" => "greenfield",   "post_code" => "wd1 8dc" }  puts formatted_address(address)   # => 20 mount park road,   #    greenfield,   #    wd1 8dc 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -