可以在不使用全局变量的情况下进行优化吗?

时间:2016-02-16 19:30:36

标签: ruby global-variables

我最近开始学习ruby,我试图避免在可能的情况下使用全局变量。我编写了下面的程序,它接受用户输入并输出用户选择的数学表(目前只是+,*但是要扩展)。我遵循https://adriann.github.io/programming_problems.html的建议让我学习。

class User_input
    .
     # multiply
     def User_input.mult1_to_12
      by = (0..12).each do | range |
        result =  $choice_int * range
        puts "#{$choice_int} x #{range} = #{result}"
      end
    end

# add
def User_input.add1_to_12
  add = (0..12).each do | range |
    result = $choice_int + range
  puts "#{$choice_int} + #{range} = #{result}"
  end
end

# accepts user input
puts "Please enter the tables you require (1-12): "
  $choice_int = gets.to_i
  puts "You have selected #{$choice_int}"
  puts "Which tables do you require (+ - * /): "
  choice_method = gets.chomp
  puts "the method you have chosen is #{choice_method}"

  if choice_method == "*"
    User_input.mult1_to_12
  elsif
    choice_method == "+"
    add1_to_12
  end
end

您会注意到我正在使用$choice的全局变量。拥有更多经验的人可以提出更优化的解决方案。请随意撕开我的代码:)谢谢。

1 个答案:

答案 0 :(得分:1)

方法可以接受参数,例如:

plot datafile  using 1:5 axes x1y1 title parameter1 with linespoints pt 7 ps 2,\
  datafile  using 1:6 axes x1y2title parameter2 with linespoints pt 7 ps 2

以下是使用参数对代码进行的简单修改:

# add numbers
def add(a,b)
  a+b
end

puts add(1,2)
# will output 3

这里有一个更漂亮的解决方案,也可以处理 - 和/(以及Ruby&Fixnsum提供的一系列其他操作):

class UserInput
  # multiply
  def self.mult1_to_12(choice_int)
    (0..12).each do | range |
      result =  choice_int * range
      puts "#{choice_int} x #{range} = #{result}"
    end
  end

  # add
  def self.add1_to_12(choice_int)
    (0..12).each do | range |
      result = choice_int + range
      puts "#{choice_int} + #{range} = #{result}"
    end
  end
end

# accepts user input
puts "Please enter the tables you require (1-12): "
choice_int = gets.to_i
puts "You have selected #{choice_int}"
puts "Which tables do you require (+ - * /): "
choice_method = gets.chomp
puts "the method you have chosen is #{choice_method}"

if choice_method == "*"
  UserInput.mult1_to_12(choice_int)
elsif choice_method == "+"
  UserInput.add1_to_12(choice_int)
end