Ruby中 respond_to? 和 send 的用法

   
 obj = Object.new
 if obj.respond_to?("talk")
   obj.talk
  else
    puts "Sorry, object can't talk!"
 end



      print "Search for: "
      request = gets.chomp
      if request == "writer"
      puts book.writer
      elsif request == "press"
      puts book.press
      elseif request == "date"
      puts book.date
      ......

以上方法可用send方法代替
      request = gets.chomp
      if book.respond_to?(request)
      puts book.send(request)
      else
      puts "Input error"
      end

你可能感兴趣的:(java,Ruby)