Can someone please give me a simple example of using ARGV in a method in ruby, i just need to understand it better, i have tried using
def greet(ARGV)
puts "Hello #{ARGV}"
end
Can someone please give me a simple example of using ARGV in a method in ruby, i just need to understand it better, i have tried using
def greet(ARGV)
puts "Hello #{ARGV}"
end
Don't use constants to collect method arguments, especially special constants like ARGV. Use positional or collected-positional arguments instead.
ARGV is a predefined global constant in Ruby. You can think of it as an Array of String values that contain the arguments passed to the Ruby interpreter, but while you technical can redefine it at runtime you should not be doing that in most cases, and certainly not redefining a global constant as part of a method definition.
ARGV[0] is the name of the file passed to the interpreter (similar to Bash's $0) while anything else is a positional parameter like Bash's positional arguments of $1 to $9. You can also get at ARGV through ARGF#argv, but that's not your use case here.
If you want to pass a single argument to a method, just give it a non-constant name. For example:
def greet(name)
puts "Hello, #{name}!"
end
If you really want to pass a variable number of arguments to a method as a named Array, then you can do that, too. For example:
def greet(*names)
names.each { |name| puts "Hello, #{name}!" }
end
%w[Alice Bob Carol].map { |name| greet(name) }
In this case, you're collecting a list of names the method-local Array names, and then iterating over the items in that Array. There are some edge cases with this that are outside the scope of your original question such as empty arrays, nil values, and passing Array objects as positional arguments, but again those edge cases are outside the scope of your original question.
Use ARGV if you're passing arguments on the command line. Otherwise, use positional arguments or collected-Array arguments in your method definitions.
try this
def greet(name)
"Hello #{name}"
end
puts greet(ARGV[0])
when you run in the terminal you enter file_name.rb user# then you enter your argument before running the file and you will get something like Hello user