Call method in same class [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
I'm new to ruby and I was wondering the following, can I call a method in the same class such as:
class myClass
$myVar = inClass
def inClass
#value = (gets data from db)
end
end
If there is a way to do this, can someone please help me?

You can do as below
class MyClass
def in_class
#value = (gets data from db)
end
def call_inclass
$my_var = in_class # don't use global variable.
end
end
Create a new instance method call_inclass and call the required class in_class from there. Your one will not work, as in_class is an instance method, and within class.. end body self is set to that class. Thus $myVar = in_class will simply thorw an error as no method error. Because $myVar = in_class it will be interpreted implicitly as $myVar = self.in_class, where self is MyClass. in_class is not a method of MyClass, rather an instance method of instances of MyClass.
Thus wrapped the method call to in_class inside another instance method, like here call_inclass.
Another way is make in_class as a singleton method of MyClass. Then it will work.
class MyClass
# again don't use global variable, rather use
# class instance variable, #my_var
$my_var = in_class
def self.in_class
#value = (gets data from db)
end
end

Related

In Ruby when you initialize a class do you set an instance variable equal to a variable? [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 8 years ago.
Improve this question
Why in ruby, when you initiazlize a class do you set the instance variable equal to a variable of the same name?
def initialize(number)
#number = number
end
We do that so that newly-created object (not a class! with initialize and #vars, you initialize the object that was just created with new() method!) remembers the value of number.
Try using this one:
def initialize(number)
end
This gets a number, but does nothing with it. When this inializer ends, the object created will not remember what was the 'number'.
Here:
def initialize(number)
#foo = 5
#bar = number
end
the newly-created object will remember a 5 in #foo and the number in #bar.
The idea to name the #variable just like the parameter is just to make it easier. In the example above, it's hard to guess what the bar is about. Instead, if I rename the #bar into #number, it wil be obvious that it holds .. the number.
def initialize(number) def initialize(number)
#bar = number <-same thing-> #number = number
end just different name end

Instance variable set inline with class definition cannot be accessed by instance method [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 8 years ago.
Improve this question
I created a Test class which has an instance variable #val and which is defined inline.
class Test
#value = 10
def display
puts #value
end
end
t = Test.new
t.display
This gives no output. But if I set #val through initialize method then the code works.
#val = 10 ( which you wrote in the scope of the class Test) creates an instance variable for your class Test. Where as initialize creates an instance variable for the instances of the class Test.
Look below, for comfirming :-
class Test
#x = 10
def initialize
#x = 12
end
end
Test.instance_variable_get(:#x) # => 10
Test.new.instance_variable_get(:#x) # => 12

May be a mistake in Metaprogramming 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 9 years ago.
Improve this question
I am reading Metaprogramming Ruby by Paolo Perrotta and I must say there is a mistake in the book,the following is the ruby code from page 70 of this book and I will past the code here again
class Computer
def initialize(computer_id, data_source)
#id = computer_id
#data_source = data_source
end
def self.define_component(name)
define_method(name) {
info = #data_source.send "get_#{name}_info" , #id
price = #data_source.send "get_#{name}_price" , #id
result = "#{name.to_s.capitalize}: #{info} ($#{price})"
return "* #{result}" if price >= 100
result
}
end
define_component :mouse
define_component :cpu
define_component :keyboard
Computer.define_component is a class method like static method in Java. What Java told us is that a static method can never access an instance attribute or an instance method without an object. So,define_component method must not use invoke define_method,which is an instance method. Logically speaking,class method was invoked before object have been created,so there is no way that #data_source and #id can be initialized(it have bean created). But here define_component invoked define_method without an instance. Is that correct?
You are missing the point slightly. The define_method will indeed not have access to the instance variables, but define_method when called on class will actually create a regular instance method. The name of this method is the parameter to define_method and the body of this new instance method is the block passed.
So define method will not actually execute the code (it can't). It will simply create a new method that can be called upon to execute the code.
I hope I got the point across.
Well, your thinking is corrupted by java. It is a strict language with strict rules. Ruby is more powerful/flexible.
def self.define_component(name)
# class scope here
define_method(name) {
# instance scope here. You can use instance-level instance variables.
}
end
define_component method defines an instance method on the class. In the body of that instance method you, naturally, can use instance variables.
Ruby doesn't have static methods. The only similarity between Ruby class methods and Java static methods is that they can both be called on classes.
In Ruby, classes are objects — they are instances of a class named Class, and they can have their own instance variables just like other object can. A class method isn't like a static method in Java — it's a singleton method of the class. You can define instance-specific methods on any object in exactly the same way.

Reader and Writer Methods [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Who can explain me the code snippets of "def name" and "def name=()"?
I don't understand why it is defined 2 times.
class Bird < Animal
def initialize(name, length)
#name
#length
end
def name
#name
end
def name=(new_name)
#name = new_name
end
end
These are getter and setter methods
bird = Bird.new("pigeon", length)
=> #<Bird:0x007f93e9b41278>
bird.name
=> "pigeon"
bird.name = 'seagull'
=> "seagull"
bird.name
=> "seagull"
Both of the methods you defined in the class are what's being called here - the call to
bird.name = 'seagull'
is actually syntactic sugar for the method call
bird.name=('seagull')
Of course, the most "rubyish" way to write these methods would be one call to attr_accessor:
class Bird < Animal
attr_accessor :name
def initialize(name, length)
#name = name
#length = length
end
end
This will give you both the getter and setter methods for the name attribute
One returns a value, one sets a value. Look at the method bodies.
def name
#name # return #name
end
def name=(new_name)
#name = new_name # set #name to your argument
end
Also, your initialize method does nothing. I assume you want to set those variables to the arguments you are taking.
def initialize(name, length)
#name, #length = name, length
end
These methods are known as "getters" and "setters", because (unsurprisingly), they 'get' or 'set' a variable.
You can also think of one as a 'command,' which will make some change to the data, and one as a 'query,' which will simply report a value (this is a helpful distinction to keep in mind when you are designing your own methods as well).
Ruby includes three class methods that define these getters and setters for you: attr_reader defines the getter, attr_writer defines the setter, and attr_accessor defines both.
You could just interact directly with the instance variable, but in most situations, code is easier to change and reason about when you use methods to access data rather than messing with the data itself.
I don't understand why it is defined 2 times.
def name to read value from #name and def name= to write value to #name.
The below is a reader(attr_reader) method
def name; #name; end # shortcut is attr_reader :name
The below is a writer(attr_writer) method
def name=(new_name) ; #name = new_name ; end # shortcut is attr_writer :name
A very good documentation What is an accessor?

referenceing object, without passing into 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 8 years ago.
Improve this question
How can I reference an object from a method without passing it as a variable?
I am getting error:
NameError: undefined local variable or method ‘my_object’ for Myclass:Class
class B
attr_accessor :somethings
include Enumerable
def initialize(*values)
self.somethings = []
end
end
my_object = B.new({d:'d'})
class Myclass
def self.my_method
p my_object
end
end
Run: Myclass.my_method
What I do NOT want to do for all my methods is...
def self.my_method(my_object)
p my_object
end
I could also solve the issue with use from a global variable
$my_object = B.new({d:'d'})
However, I only really want to make the variable available to my methods in Myclass class.
I only really want to make the variable available to my methods in Myclass class.
Then you should define it as an instance variable in corresponding scope of Myclass. As it is now, my_object is a local variable and is not visible because of the scope gate.
class Myclass
#my_object = B.new({d:'d'})
def self.my_method
p #my_object
end
end

Resources