Call class methods inline to create a new object [closed] - ruby

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 9 years ago.
Improve this question
Trying to figure out if I can pass arguments to a class without creating a new object. I tried as below
Filename: display.rb
class Print
def initialize(name)
#name = name
end
def disp
p #name
end
end
init = Print.new(ARGV[0])
init.disp
Terminal
> ruby display.rb "ross"
# => "ross"
[EDIT] I don't want to call init = Print.new(ARGV[0]) and init.disp in the file; instead, I want to pass it as command line argument ruby display.rb "ross", and it should display the name. How can I achieve this?

Here's an idea. Load the rb file and execute some inline ruby afterwards:
ruby -r"./display.rb" -e "Print.new('ross').disp"

Add an option parser to your script and then properly instantiate the Print class from the option parser. The option parser will handle the work of reading in the ARGV array and you can use the Print class in an OO manner as it is intended.

You could call ruby display.rb "ross" if you weren't using a class, and just running straight Ruby code. For example, let's say your file looks like this:
puts ARGV[0]
You could now run this as ruby display.rb "ross" and your argument will get printed.
Another options would be to setup your function like this:
class Print
def self.disp(yourinput)
puts yourinput
end
end
Which in this case, you could then call you function directly from the class, without needing to instantiate the class. For what you are trying to achieve, this may be your best solution.
Print.disp(ARGV[0])

You can use the allocate method to create an object of a class.
But I think you are really asking if you can create and call a class method.
Print.disp(ARGV[0]) can definitely be done.
class Print
def self.disp(something)
puts something
end
end
Print.disp(ARGV[0])
And you would call it like this:
$ ruby display.rb Ross
And it would output:
Ross

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

Passing arguments through parameter in 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 years ago.
Improve this question
I am passing an argument using implicit return.
Point out what's wrong please, Ruby does not provide any feedback error for the implicit return, it is just blank with no response.
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
add(20, 45)
subtract(80, 10)
I know it works in terminals. Is that the only way to work this code? I know the puts way to make this work using code editor that forces an implicit return that is not nil.Trying to do the same with this method.
If you're using a read-evaluate-print-loop (REPL) like irb then you'll see the output of your code as you type it in. If you're in a code editor you probably will not.
Here's how to get some output from that code:
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
p add(20, 45)
p subtract(80, 10)
Putting p before any given thing will give you a quick inspect (debug) view into the object in question. Normally Ruby will just throw away any results in a void context like this, you're not asking it to preserve the results of these method calls anywhere, nor display it in any form, which is why there's no output.
I have my editor configured to run Ruby code with the push of a button, so maybe yours has an option to do that as well. Most do it in some form but it may require some configuration.

ruby inheritence failure I can't undertand [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I can't understand why the following code give error
./nodes.rb:14:in `initialize': wrong number of arguments (1 for 0) (ArgumentError)
from ./nodes.rb:14:in `initialize'
from ./nodes.rb:23:in `initialize'
from ./nodes.rb:31:in `new'
from ./nodes.rb:31:in `<main>'
Can someone please enlighten me?
class Base
def initalize(msg)
print "########## This is the Base class ###########"
end
end
class A < Base
attr_accessor :var_a
def initialize(msg)
super
var_a = "AAAAA"
print "########### From A: #{msg} VAR: #{var_a} ########################\n"
end
end
class B < A
attr_accessor :var_b
def initialize(msg)
super
var_b = "BBBBB"
print "########### From B: #{msg} VAR: #{var_b} ########################\n"
binding.pry
end
end
b = B.new("test")
no = A.new("This is 'A'")
The other posters are correct that you spelled "initialize" wrong in your code.
Something to be aware of when using super in ruby - when calling "super" by itself it will pass all arguments given to the current method. So in your case it was passing msg to a new Base class. Because you spelled initialize wrong, it wouldn't accept any arguments hence why you were getting a (1 for 0) error.
If you kept your current code and used super() it would call the super method without any arguments, and work. Albeit with the error, but this would be able to run. Using super with the empty parenthesis is one of the only time I can think of where this will make a difference.
You spelled initialize wrong in Base. So, the super call in A refers to the default Object#initialize which doesn't take any arguments.
You have a typo in:
class Base
def initalize(msg)
It should be initialize. So Ruby uses the default initialize that takes no argument, causing the ArgumentError you saw.
super invokes a method with the same name as the current method in the superclass of the current class. It is invoking initialize in each of the parent classes and needs a msg.

Why should I use lambda/proc ?Explain it's importance [duplicate]

This question already has answers here:
When to use lambda, when to use Proc.new?
(14 answers)
Closed 8 years ago.
I am new to ruby, and while learning it I didn't understand the concept of lambdas or procs. I know lambda and proc are the blocks of code that have been bound to a set of local variables. But I don't understand their use.
So
what advantage does a programmer get from it?
I had asked this question in past and got marked as duplicate and was given a link that had totally unrelated answered so please before marking it as duplicate or scolding me please view the answers of other links by yourself first.
This is a broad question. You're basically asking "why are closures important?". Two uses that come to mind for me are:
DISCLAIMER: I haven't actually run any of this code, but it should get the point across.
Delayed execution of code. If I want to pass some code as a callback (e.g. Rails' after_create), I can use a closure to "hook" into Rails by passing a block. That block has the context of the current class, but it doesn't need to get run until Rails says so.
class SuperClass
def self.after_create(&block)
#__after_create = block
end
def self.create
# do normal create logic
instance = self.new
if #__after_create
#__after_create.call(instance)
end
end
end
class MyClass < SuperClass
after_create {|instance| instance.log}
def log
puts 'hello world!'
end
end
MyClass.create
Passing functions as parameters. This makes it easier to do things like write a generic tree traversal algorithm that just passes each node of the tree to some function:
def Tree.elements
["hello", "world!"]
end
def Tree.traverse(&block)
elements.each {|el| block.call(el)}
end
Tree.traverse {|el| puts el} # "hello" "world!"
Tree.traverse {|el| puts el.size} # "5" "6"

How to get the name of the calling method?

is there a way in Ruby to find the calling method name inside of a method?
For example:
class Test
def self.foo
Fooz.bar
end
end
class Fooz
def self.bar
# get Test.foo or foo
end
end
puts caller[0]
or perhaps...
puts caller[0][/`.*'/][1..-2]
In Ruby 2.0.0, you can use:
caller_locations(1,1)[0].label
It's much faster than the Ruby 1.8+ solution:
caller[0][/`([^']*)'/, 1]
Will get included in backports when I get the time (or a pull request!).
Use caller_locations(1,1)[0].label (for ruby >= 2.0)
Edit: My answer was saying to use __method__ but I was wrong, it returns the current method name.
I use
caller[0][/`([^']*)'/, 1]
How about
caller[0].split("`").pop.gsub("'", "")
Much cleaner imo.
Instead you can write it as library function and make a call wherever needed. The code goes as follows :
module CallChain
def self.caller_method(depth=1)
parse_caller(caller(depth+1).first).last
end
private
# Copied from ActionMailer
def self.parse_caller(at)
if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at
file = Regexp.last_match[1]
line = Regexp.last_match[2].to_i
method = Regexp.last_match[3]
[file, line, method]
end
end
end
To trigger the above module method you need to call like this:
caller = CallChain.caller_method
code reference from
In order to see the caller and callee information in any language, whether it be ruby or java or python, you would always want to look at the stack trace. In some languages, such as Rust and C++, there are options built into the compiler to turn on some sort of profiling mechanism you can view during run time. I do belive one exists for Ruby called ruby-prof.
And as mentioned above, you could look into the execution stack for ruby. This execution stack is an array containing backtrace location objects.
Essentially all you need to know about this command is as follows:
caller(start=1, length=nil) → array or nil

Resources