ruby - How to refactor the below code in such a way that if I made changes in display_home_page method I need not to make changes in the process method -


below 2 methods: 1 display_home_page: display on console, , 2 process: calling method based on user input on choice variable.

def display_home_page   print "  1 timeline\n  2 tweet\n  3 other's  timeline\n  4 retweet\n  5 follow\n  6 wall\n  7 logout\nenter choice : " end  def process(choice)   if choice == "1"     my_timeline   elsif choice == "2"     tweet   elsif choice == "3"     others_timeline   elsif choice == "4"     re_tweet   elsif choice == "5"     follow   elsif choice == "6"     my_wall   else     error_message   end end 

perhaps this:

mapping = {   '1' => 'my timeline',   '2' => 'tweet',   '3' => "other's timeline",   '4' => 'retweet',   '5' => 'follow',   '6' => 'my wall',   '7' => 'logout' }  def display_home_page   mapping.each |number, method|     puts "  #{number} #{method}"   end    puts 'enter choice :' end  def process(choice)   method = mapping.fetch(choice, 'error_message')    send(method.downcase.gsub(' ', '_').gsub("'", '')) end 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -