What does method_name(*) mean? [duplicate] - ruby

This question already has an answer here:
naked asterisk as parameter in method definition: def f(*)
(1 answer)
Closed 8 years ago.
In the rails code I came across following method definition def initialize(*)
I understand what def foo(*a) means but can't figure out significance of omitting identifier name after *. How do you access any arguments passed to this method?

Here's my guess.
It works because of second line:
def initialize(*)
super
...
end
So the method receives arbitrary number of arguments and passes all of them to super(as you know, super without arguments means take all arguments from original method).
And then in this case the names for arguments are not required.

Related

how to use ARGV in a method in a ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
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
TL;DR
Don't use constants to collect method arguments, especially special constants like ARGV. Use positional or collected-positional arguments instead.
Using ARGV Generally Implies Command-Line Arguments
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.
Passing Positional Arguments to a Method
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.
Summary
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

What does the `&:symb` do? [duplicate]

This question already has answers here:
What does map(&:name) mean in Ruby?
(17 answers)
Closed 4 years ago.
I've seen an example of how to sort a string. To sort case insensitively:
str.chars.sort(&:casecmp).join
#=> "ginrSt"
I'm curious about (&:casecmp). I found that for example:
arr.map(&:name)
is shorthand for
arr.map(&:name.to_proc)
which is same with
arr.map{|el| el.name}
I know the & (ampersand) tries to convert symbol to proc, and pass it as a block to a method. I do not understand how this would work for sort method, which is supposed to compare two values. Would it be as follows?
str.chars.sort{|a, b| a.casecmp ;b.casecmp}.join
It wouldn't be helpful since soft needs a block to return an integer and casecmp needs an argument. (Or is it called parameter in that case?) To me, it looks more like this:
str.chars.sort{|a, b| a.casecmp(b)}.join
How does &:casecmp know to take one of |a, b| as a caller and the other one as an argument? I wouldn't guess it that it is an option.
If more than one parameter is passed to your block, the proc created by Symbol#to_proc uses the additional block parameters as parameters to the method call.
http://phrogz.net/symbol-to-proc-with-multiple-arguments
So, what's really happening is, sort(&:casecmp) is converted to:
sort {|a,b| a.casecmp(b) }
because sort takes two parameters.

no implicit conversion of Symbol into Integer, Ruby [duplicate]

This question already has an answer here:
Ruby, no implicit conversion of Symbol into Integer
(1 answer)
Closed 6 years ago.
I am new to ruby, and have no idea, how to fix this error. when i run my script containing the code below, i always get the error: 'no implicit conversion of Symbol into Integer. I think the Problem is in the lines #killProc..., #Name=..., and #working_directory.
Can you tell me whats wrong?
Thanks for your help
class RubyCommand
include Patir::Command
attr_reader :cmd,:working_directory,:killProc
def initialize params,&block
#killProc=params[:killProc]
#name=params[:name]
#working_directory=params[working_directory]||"."
if block_given?
#cmd=block
else
raise "You Need to provide a block"
end
end
end
Pretty sure you're passing an array instead of a hash. You should call it like this:
RubyCommand.new({killProc:1,name:"test"})

Use 'puts' with block accepting method over multiple lines [duplicate]

This question already has answers here:
Ruby Print Inject Do Syntax
(3 answers)
Closed 7 years ago.
Let's say I have the following (working) pseudo-code:
puts results.fields.inject('') { |string, key|
lengths[key] = calculate_length(key)
string << format(key)
}
Following the ruby-style-guide I should
Omit parentheses for 'keyword methods', i.e. puts, (which would create }) or end) anyway)
Use do...end for multi-line blocks
However, when replacing {...} with do...end it raises
undefined method `' for :title:Symbol (NoMethodError)
Therefore, is it possible to refactor this code without violenting the guideline?
There is a difference in precedence between {} and do end
If you use do end the block is associated with the puts statement, whereas the braces are associated with the results.field.inject('')
If you want to use do end then you have to remove the ambiguity of association by parentheses. It's one of those "gotchas" where the guidelines are recognized as guidelines, not absolute rules.
See also this answer...
In Ruby, why is a method invocation not able to be treated as a unit when "do" and "end" is used?

What does a single splat/asterisk in a Ruby argument list mean? [duplicate]

This question already has an answer here:
naked asterisk as parameter in method definition: def f(*)
(1 answer)
Closed 10 years ago.
I was poking through the Rails 3 ActiveRecord source code today and found a method where the entire parameter list was a single asterisk.
def save(*)
I couldn't find a good description of what this does (though I have some ideas based on what I know about splat arguments).
What does it do, and why would you use it?
It means it can have any number of arguments (including zero) and it discards all those arguments.

Resources