ruby inheritence failure I can't undertand [closed] - ruby

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.

Related

initialize method with argument is not recognizing the argument [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 am building a rather simple Module::Class with a initialize method.
module Encryption
class Caesar
def initalize(number)
#caesar_number = number
end
end
end
when I run Encryption::Caesar.new(2) i get the following error:
ArgumentError: wrong number of arguments (1 for 0)
from (irb):32:in `initialize'
from (irb):32:in `new'
from (irb):32
from /Users/yedidyaweiner/.rvm/rubies/ruby-2.1.3/bin/irb:11:in `<main>
If i run Encryption::Caesar.new, it successfully creates a new instance of the class.
Why is the error saying that it does not expect an argument when it is defined in the initialize method?
initalize is misspelled; it should be initialize.
module Encryption
class Caesar
def initialize(number)
#caesar_number = number
end
end
end
foo = Encryption::Caesar.new(2)
foo.inspect #=> #<Encryption::Caesar:0x1e05580 #caesar_number=2>

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"

Call class methods inline to create a new object [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 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

Accidental NilClass in my instance variables [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am making a dating simulator. One of the first things I need is to keep track of the way characters feel about each other. In this sim, anyone can date anyone else, and there are two variables for relationship (one for love and one for friendship).
So I thought the easiest way to do this would be for each character to have a separate class that kept track of how they felt about everyone else. Below is one such sample class. I also thought that the easiest way to keep track of where points should be added was by giving each character a hash that pointed to their own variable, and then using a swap function to trade targets with the person they are speaking to.
However, I am getting an error message.
class HRelatStatus
def initialize
{#target=> #hrelat}
#krelat =[10, 10]
#arelat =[9, 4]
#srelat =[13, 11]
#jrelat =[12, 1]
#brelat =[5, 5]
#hrelat=[0, 0]
end
def dataaccess
attr_accessor :target, :krelat, :arelat, :srelat, :jrelat, :brelat, :hrelat
end
def makehappy
#target[0] = #target[0]+1
end
end
hfeels=HRelatStatus.new
puts #krelat.class
puts #krelat[1]
hfeels.makehappy
puts #target[0]
When I try to run this, #krelat comes back as a Nil class. And when I try to run the makehappy method (or any method, really) I get the error message undefined method '[]' for nil class.
How do I stop my instance variables from being nil classes? How can I sucessfully make methods that will add to one variable in the array for a specific character? And does anyone have a better idea for how I can specify who to target?
You are saying:
hfeels=HRelatStatus.new
puts #krelat.class
But there is no such thing as #krelat in this context. What you are after is the krelat instance variable inside your instance, i.e. hfeels.krelat.
(Of course, that won't work either because you've hidden your accessor generators inside an instance method.)
The first thing you actually need to do is learn how Ruby (or really, variable scope in any language) works.
#krelat outside of the class is totally unrelated to #krelat inside the class.
The makehappy method won't work because { #target => #hrelat } doesn't do anything in Ruby (well, it creates a hash with a nil key pointing to a nil value and then discards that hash. Ie. effectively nothing.
This code is a total mess, learn Ruby first. Buy "Programming Ruby" and read it.

Understanding [ClassOne, ClassTwo].each(&:my_method) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does map(&:name) mean in Ruby?
I was watching a railscast and saw this code.
[Category, Product].(&:delete_all)
In regards to clearing a database.
I asked about the line in IRC and was told
(&:delete_all)
was a shortcut for
{|model| model.delete_all}
I tested this with the following
class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
I received an error saying
Wrong Argument type Symbol (expected Proc)
I also tried
one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
But that still failed.
If I modified it to read
[one, two].each{|model| model.class_method}
Everything worked as expected.
So, what does &:delete_all actually do? The docs say delete_all is a method, so I am confused as to what is going on here.
This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
I believe Rails defines this in ActiveSupport.
It's some Rails specific patching of Ruby, symbol to proc.

Resources