Вопрос:

Calling a Method using the Input of the User (using their String)

ruby

44 просмотра

1 ответ

5 Репутация автора

I am attempting to use the String from a variable to call a Method within the program.

How can one use the String from the Variable to call said Method without having to nest or make multiple checks?

module Player
  @@location = "location"

  def Player.input(input)
    if input == "look"
      "Call Method from @@location"
    end
  end

  def Player.set_location(input)
    @@location = input
  end
end

def input
  print "> "
  Player.input(@stdin.gets.chomp)
end

def "name of Method can be same as @@location"
  ...
end

def "another name of Method can be same as @@location"
  ...
end

def "another name, etc"
  ...
end
Автор: Planet_Earth Источник Размещён: 08.11.2017 11:46

Ответы (1)


0 плюса

3030 Репутация автора

Решение

What do you mean by without having to nest ? I wonder if your code is a contrived example. Defining methods in the special object main is OK for a quick test, if they are also called from main, otherwise they must be put in a class.

So the answer could be as simple as that :

module Player
  @location = 'location'

  def Player.input(input)
    puts "in Player.input(#{input})"
    if input == 'look'
      puts "Calling method <#{@location}>"
      Switch.send(@location)
    else
      puts 'wrong input, must be "look"'
    end
  end

  def Player.set_location(input)
    @location = input
  end
end

def input
  print "> "
  Player.input(gets.chomp)
end

class Switch
    def self.abc
      puts 'in abc'
    end

    def self.def
      puts 'in def'
    end

    def self.location
      puts 'in location'
    end

    def self.method_missing(name, *args, &block)
      puts "There is no method #{name} in #{self.name}" 
    end
end

input
input
Player.set_location('abc')
input
Player.set_location('xyz')
input

Execution :

$ ruby -w t.rb 
> looc
in Player.input(looc)
wrong input, must be "look"
> look
in Player.input(look)
Calling method <location>
in location
> look
in Player.input(look)
Calling method <abc>
in abc
> look
in Player.input(look)
Calling method <xyz>
There is no method xyz in Switch
Автор: BernardK Размещён: 09.11.2017 07:34
Вопросы из категории :
32x32