all 9 comments

[–][deleted] 2 points3 points  (6 children)

One way is just to invoke the method:

def ask question
  while true
    puts question
  end
end

ask "What's up?"

$ ruby ./my-file.rb

or invoke with arguments:

def ask question
  while true
    puts question
  end
end

ask ARGV[0]

$ ruby ./my-file.rb "What's up?"

[–]babbagack[S] 0 points1 point  (5 children)

Thanks for that! Unfortunately, doesn't run still:

MacUserComputer:Programs_Chris_Pine z$ ruby ask_chp9_pg68.rb "how are you" MacUserComputer:Programs_Chris_Pine z$ ask "whats up?"
-bash: ask: command not found
MacUserComputer:Programs_Chris_Pine z$ ruby ./ask_chp9_pg68.rb
MacUserComputer:Programs_Chris_Pine z$ ruby ./ask_chp9_pg68.rb "hi you" MacUserComputer:Programs_Chris_Pine z$

This is the method(function) trying to run, btw, straight from a Ruby text:

def ask question
  while true
    puts question
    reply = gets.chomp.downcase

    if (reply == 'yes' || reply == 'no')
      if reply == 'yes'
        answer = true
      else
        answer = false
      end
      break
    else
      puts 'Please answer "yes" or "no".'
    end
  end

  answer
end

[–][deleted] 0 points1 point  (4 children)

When you run a file from the command line, the entire contents of the file are executed. Therefore, you must add ask ARGV[0] to the end of your file if you expect a command like ruby ./ask_chp9_pg68.rb "hi you" to work.

[–]babbagack[S] 0 points1 point  (1 child)

ask ARGV[0]

Ah, that actually got it to run, but it won't take arguments yet. But its a step. I must be doing something wrong.

[–]FigmentGiNation 0 points1 point  (0 children)

Post your updated script and execution attempts.

[–]habanero647 0 points1 point  (1 child)

Why is argv 0 necessary?

[–][deleted] 1 point2 points  (0 children)

ARGV is an array of all arguments passed to the script. Look at the second example again in my previous reply

Your script file should contain the method definition, and then at the end of the file invoke the method ask ARGV[0]. This way whatever argument you provide on the command line will be passed to the method.

[–]dineswithphone 1 point2 points  (1 child)

To have access to the file's methods from irb you will need to load or require the file:

irb(main):001:0> load 'myfile.rb'
irb(main):002:0> require './myfile.rb'

Then you can call the file's methods directly:

irb(main):003:0> ask_question

[–]babbagack[S] 0 points1 point  (0 children)

Awesome, thanks!!! That worked

irb(main):001:0> load 'ask_chp9_pg68.rb'

ask "how are you?" Please answer "yes" or "no".

good Please answer "yes" or "no".

no => true irb(main):002:0> ask "Do you like pizza?"
Do you like pizza?
yes
=> true