Sean
Sean

Reputation: 11

why my .rb script isn't putting to bash?

I've got a simple code for a class. It's:

def greeting
 greeting = ARGV.shift
  ARGV.each do |arg|
     p "#{greeting}, #{arg}!"
     end
  end

My desire is for it to simply output "Hello, Charlie!" and "Hello, Sam!" based on the names stored in the array. However when I try to run the program in ruby it looks like I used a return statement.

 address_bloc :> ls
 address_bloc.rb greeting.rb     ruby
 argv_test.rb    models          spec

 address_bloc :> greeting.rb Yo Tommy Bob Sally
 -bash: greeting.rb: command not found

 address_bloc :> ruby greeting.rb Yo Sam Sean Bill

 address_bloc :> ruby greeting.rb Yo Sam Sean Bill

Upvotes: 0

Views: 60

Answers (1)

user108471
user108471

Reputation: 2607

Remove the function definition logic and just include the contents at the top-level if this is all you want your script to do:

greeting = ARGV.shift
ARGV.each do |arg|
  puts "#{greeting}, #{arg}!"
end

If you want to continue with defining a general-purpose function for greeting a list of names, you may also do so by calling greeting and passing it the contents of ARGV, as in the following:

def greeting(args)
  greeting = args.shift
  args.each do |arg|
    puts "#{greeting}, #{arg}!"
  end
end
greeting ARGV

But in general, it's a nicer function if its arguments are more meaningful, so consider doing something like this:

def greet_list(greeting, name_list)
  name_list.each do |arg|
    puts "#{greeting}, #{arg}!"
  end
end
greet_list ARGV.shift, ARGV

Upvotes: 4

Related Questions