How do I define an instance method in Ruby? [duplicate] - ruby

This question already has answers here:
What does a Java static method look like in Ruby?
(2 answers)
Closed 8 years ago.
I'm trying to define a method called function. It works when I do this:
a = A.new
def a.function
puts 100
end
But I want the method to work for any instance variable, not just a. For example, when I call function on an instance of A other than a, nothing happens. So I used A::f to define the function rather than a.function.
class A
attr_accessor :function
attr_accessor :var
end
def A::function
self.var = 0x123
end
a = A.new
a.function
puts a.var
This compiles fine but when I try to call the function I get an error. Why is it not working and how can I do what I'm attempting?

You're really tangled up here. I suggest you check out _why's poignant guide to ruby and get a handle on what is going on here.
As an attempt to steer you right, though…
a isn't an instance variable. It's a local variable that you're using to reference an instance of A.
def a.foo defines a method on the eigenclass of a.
attr_accessor :function already defined A#function (that is, an instance method on A called function) that essentially looks like this: def function; #function; end
def A::function defines a class method on A that you could access via A.function (not an instance of A as in a.function.
MRI doesn't really compile ruby like you might anticipate. It runs it, dynamically interpreting statements in realtime.
You probably want to stick with defining standard instance methods in the traditional manner, and avoid using “function” as a placeholder name since it is a reserved word and has special meaning in other languages. I'll use “foo” here:
class A
def foo
'Awww foo.'
end
end
That's it, you can now create an instance of A (a = A.new) and call foo on it (a.foo) and you'll get back 'Aww foo.'.

class A
def function
puts 100
end
end
a = A.new
a.function #=> "100"
That's a classic instance method. Is that what you're looking for or am I missing something?

If you're trying to define methods dynamically, you could use Class#define_method. Otherwise, if you are just wanting to define the method for the class, defining it in the scope of class A will suffice.
Anyway, could you be more specific on what are you trying to accomplish and what kind of error you're having, please?

Related

What is the scope of variables and methods included via ruby modules?

Suppose I have the following:
module MyModule
module SubModule
Var = 'this is a constant'
var = 'this is not a constant'
def hello_world
return 'hello world!'
end
end
end
In the same file, I can only seem to access MyModule::SubModule::Var, but not any the constant or the method. If I now create a class and include these modules in different ways, I get additional strange behavior:
class MyClass
include MyModule
def initialize()
puts SubModule::Var
end
def self.cool_method
puts SubModule::Var
end
end
In this case, I can again only access Var, but not the other two. SubModule::var and SubModule::hello_world do not work. Finally:
class MyClass
include MyModule::SubModule
def initialize()
puts Var
puts hello_world
end
def self.cool_method
puts Var
puts hello_world
end
end
In this case, I can now access both Var and the method hello_world but not var, and, the weirdest thing, is that hello_world appears to have become an instance method! That is, the call to hello_world in initialize works, but the one in self.cool_method doesn't. This is pretty strange, considering that Var seems to have been included as a class variable, since outside the class, I must access them like so:
MyClass::Var
x = MyClass.new
x.hello_world
So, I have a few major questions.
What is going on behind the scenes with regards to Var vs var? It appears that capitalizing a variable name is more than just a convention after all.
When includeing a module, what kinds of things are passed to the including class, and at what scope?
Is there a way to do the opposite? That is, use include to include an instance variable or a class method?
What is going on behind the scenes with regards to Var vs var? It appears that capitalizing a variable name is more than just a convention after all.
Yes, of course, it's not a convention. Variables which start with an uppercase letter are constants, variables which start with a lowercase letter are local variables. The two are completely different.
When includeing a module, what kinds of things are passed to the including class, and at what scope?
Nothing gets passed anywhere. includeing a mixin simply makes that mixin the superclass of the class you are includeing it into. That's all. Everything else then works exactly as with classes.
Is there a way to do the opposite? That is, use include to include an instance variable or a class method?
I don't understand this question. Instance variables have nothing to do with mixins or classes. They belong to instances, that's why they are called "instance" variables.
There are no such things as "class methods" in Ruby. Ruby only knows one kind of methods: instance methods. When Rubyists talk to each other, they will sometimes use the term "class method" to mean "singleton method of an object that happens to be a class", but they do that knowing full well that class methods don't actually exist, it's just a shorthand in conversation. (And, of course, singleton methods don't exist either, they are just a convenient way of saying "instance method of the singleton class".)

Creating instance variables in Ruby

This question is regarding programming practices in Ruby.
Is it preferable to create instance variables in ruby inside a static method? Or should they be created in an initialize method?
Well initialize is made for that, why would you do something different.
class SomeClass
def initialize(first, second)
#first = first
#second = second
end
end

calling a nonstatic function in ruby

I am confused how to call a function defined in a class inside another function defined in that same class. Here is what I have done:
class Test
def TestFunc(obj)
puts obj
end
def Test.StatFun(obj)
puts obj
TestFunc(obj)
end
end
Test.StatFun([[5,2], [4,3]])
When I run this in cmd.exe, I get the following error:
ruby LawtonTest.rb 5 2 4 3 LawtonTest.rb:10:in StatFun': undefined
methodTestFunc' for Test:Class (NoMet hodError)
from LawtonTest.rb:14:in `'
I can't figure it out. Any help would be greatly appreciated.
You have to call it on the object. I think you need a good reference of oop in Ruby, take a look at http://zetcode.com/lang/rubytutorial/oop/. But anyway, the thing is, methods (which is what you declare with def) have to be called on an object, not like a global function. So if you want to use TestFunc, try this:
def Test.StatFun(obj)
puts obj
Test.new.TestFunc(obj)
end
The Test.new part is used to create an object, on which you can use the TestFunc method.
I can't see a definition for TestFunc anywhere. Have you defined it?
Also, the general Ruby convention is to use lowercase names for methods (eg test_func)
edit should really read the question before answering...
The problem here is that TestFunc is only defined for instances of the class Test, whereas when you call Test.StatFun, the object executing the code is the actual class Test. This means that it doesn't know what TestFunc is. One way to get around this is to create a new instance (because that is one thing classes do know how to do):
def Test.StatFun(obj)
puts obj
new.TestFunc(obj)
end

Which method to define on a Ruby class to provide dup / clone for its instances?

I have a Pointer class with a single attribute :contents, that points to an object of class MyObject.
class MyObject
def hello; "hello" end
end
class Pointer
attr_reader :contents
def initialize( cont ); #contents = cont end
# perhaps define some more state
end
I want my Pointer to be able to make copies of itself. I know that #dup method is defined by default, while #clone method is expected to be overriden to be able to make deep copies. But here, the copies don't have to be too deep. So, the first dilemma that I have is, should I override #dup method, because I don't really want to copy the additional state of my Pointer, just make a new one pointing to the same MyObject instance? Or should I refrain from overridine #dup, because I am not "supposed to" and override #clone with a method making shallow copies?
I would welcome comments on the above, but let's say that I will choose to override #dup. I could do just this:
class Pointer
def dup; self.class.new( contents ) end
end
But online, I read something like "the dup method will call the initialize copy method". Also, this guy writes about #initialize_clone, #initialize_dup and #initialize_copy in Ruby. That leaves me wondering, is the best practice perhaps like this?
class Pointer
def initialize_copy
# do I don't know what
end
end
Or like this?
class Pointer
def initialize_dup
# do I don't know what
end
end
Or should I just forget about online rants written to confuse beginners and go for overriding #dup without concerns?
Also, I do understand that I can just call #dup without defining any custom #dup, but what if I want to define #dup with different behavior?
Also, the same question apply to #clone - should I try to define #initialize_clone or just #clone?
From my experience, overloading #initialize_copy works just fine (never heard about initialize_dup and initialize_clone).
The original initialize_copy (which initializes every instance variable with the values from the original object) is available through super, so I usually do:
class MyClass
def initialize_copy(orig)
super
# Do custom initialization for self
end
end

referring to module level variables from within module

I'm having some difficulty with referring to module-level variables in ruby. Say I have a situation like this, where I'm referring to M.a internally:
module M
##a=1
def self.a
##a
end
class A
def x
M.a
end
end
end
Now, this example works fine for me but it is failing in a slightly more complicated context (where the module is spread over a number of files installed in a local gem - but my understanding is that that should not effect the way the code is executed) with an error like this: undefined method `a' for M::M (NoMethodError).
So, is this the correct way to refer to module level variables in context? is there a simpler/more idiomatic way?
If the module is spread out over other files, you need to ensure that your initialization is run before the method is called. If they are in the same file, this should be as much as guaranteed, but if you somehow split them there could be trouble.
I've found you can usually get away with this:
module M
def self.a
#a ||= 1
end
end
If this variable is subject to change, you will need a mutator method. Rails provides mattr_accessor that basically does what you want, part of ActiveSupport.

Resources