Is there a way to use an integer as a method name in Ruby?

Here is an example of what I'm trying to do:

def 9() run_playback_command(NINE_COMMAND) end 

I would like it to be because it was to be used later:

 if(channelNumber != nil) splitChannel = "#{channelNumber}".split(//) if(splitChannel[3] != nil) response = "#{splitChannel[3]}"() end if(splitChannel[2] != nil) response = "#{splitChannel[2]}"() end if(splitChannel[1] != nil) response = "#{splitChannel[1]}"() end if(splitChannel[0] != nil) response = "#{splitChannel[0]}"() end end 

Sorry to bother if this is a simple question! I am very new to Ruby.

Edit:

Here is what I'm trying to get Siri to do:

 if(phrase.match(/(switch to |go to )channel (.+)\s (on )?(the )?(directv|direct tv)( dvr| receiver)?/i)) self.plugin_manager.block_rest_of_session_from_server response = nil if(phrase.match(/channel \s([0-9]+|zero|one|two|three|four|five|six|seven|eight|nine)/)) channelNumber = $1 if(channelNumber.to_i == 0) channelNumber = map_siri_numbers_to_int(channelNumber) end channelNumber.to_s.each_char{ |c| run_playback_command(COMMAND[c]) } end 

No wonder he doesn't read the channel. Help?

+4
source share
2 answers

That's what you need?

 COMMAND = { "0" => ZERO_COMMAND, "1" => ONE_COMMAND, "2" => TWO_COMMAND, #... "9" => NINE_COMMAND } channelNumber.to_s.each_char{ |c| run_playback_command(COMMAND[c]) } 

You don’t even need to check nil? , since nil.to_s is an empty string, and therefore each_char iterator each_char not process any characters.

Aside, you cannot define (or call) a method whose name is not a legal identifier (you cannot start with a number) using standard syntax, but this is technically possible:

 class Foo define_method "9" do puts "It nine!" end end f = Foo.new c = "9" f.send(c) #=> "It nine!" p (f.methods - Object.methods) #=> [:"9"] 
+7
source

we have the right solution:

 callbacks = {"9" => lambda { run_playback_command(NINE_COMMAND) } } if channelNumber splitChannel = channelNumber.to_s.split(//) splitChannel.each do |number| callbacks[number].call end end 

Your ifs collection is a very verbose way of writing splitChannel.each .

+4
source

Source: https://habr.com/ru/post/1382757/


All Articles