3

私はRubyにかなり慣れていません。私は大学生で、通常の c をカバーするプログラミング コースを受講したばかりです。クラスの最終プロジェクトは、かなり簡単なスロップ インターセプト プロジェクトでしたが、すべてに関数を使用する必要がありました。次に例を示します。

#include <stdio.h>
#include <math.h>

int get_problem(int *choice){
  do {
  printf("Select the form that you would like to convert to slope-intercept form: \n");
  printf("1) Two-Point form (you know two points on the line)\n");
  printf("2) Point-slope form (you know the line's slope and one point)\n");
  scanf("%d", &*choice);
  if (*choice < 1 || *choice > 2){
      printf("Incorrect choice\n");}
  }while (*choice != 1 && *choice !=2);
  return(*choice);
}
...
int main(void);
{
  char cont;
    do {

  int choice;
  double x1, x2, y1, y2;
  double slope, intercept;
  get_problem (&choice);
...

プログラム全体を完了する関数がさらにいくつかあります。私は新しい仕事を得て、Ruby の学習を開始する必要があるため、最初のプロジェクトでこのプログラムを Ruby に変換したいと考えていましたが、今では単純に関数を取り除き、メソッドやプロシージャなしで実行することができました。同じことを実行してメソッドを定義し、入力を与えずにメソッドを呼び出して、メソッドに格納されている変数を取得できるかどうかを知りたかったのです。メソッドまたはプロシージャを使用して可能でしょうか。これは、procを使用してこれまでに行ったことの一部です。

get_problem = Proc.new {
begin
puts "Select the form that you would like to convert to slope-intercept form: "
puts "1) Two-Point form (you know two points on the line)"
puts "2) Point-slope form (you know the lines slope and one point)"
choice = gets.chomp.to_i
if (choice < 1 || choice > 2)
    puts "Incorrect choice"
    end 
end while (choice != 1 && choice !=2)
}
....
begin
get_problem.call
case choice
when 1
    get2_pt.call
    display2_pt.call
    slope_intcpt_from2_pt.call
when 2
    get_pt_slope.call
    display_pt_slope.call
    intcpt_from_pt_slope.call

今、私はおそらくそれがすべて間違っていることを知っていますが、試してみることにしました. 私が持っていた場所の前にメソッドとして持っています

def get_problem(choice)
....
end
....
get_problem(choice)
....

私が見逃している基本的なものはありますか?ご覧のとおり、私は c でポインターを使用し、メインで変数を初期化する必要がありました。

私を助けてくれてありがとう。ロバート

4

1 に答える 1

4

Ruby では変数にポインターを渡すことはできませんが、目的を達成するためにポインターを渡す必要はないと思います。これを試して:

def get_problem
  puts "Select the form that you would like to convert to slope-intercept form: "
  puts "1) Two-Point form (you know two points on the line)"
  puts "2) Point-slope form (you know the lines slope and one point)"

  loop do
    choice = gets.chomp.to_i
    return choice if [1, 2].include? choice
    STDERR.puts "Incorrect choice: choose either 1 or 2"
  end
end

choice = get_problem
puts "The user chose #{choice}"

これは、ユーザーが または のいずれかをget_problem選択するまでループし、選択した番号を返すメソッドを定義します。この番号はトップレベルの変数に格納できます。12choice

于 2013-03-12T01:44:52.507 に答える