I have a BankAccount class. I was trying to create multiple instances of this class and put them into an array. For example
accounts = [Ba1 = BankAccount.new(100), Ba2 = BankAccount.new(100)]
I want to initialize the array with a large number of instances inside, let's say 20, so from Ba1 to Ba20. Is there an easier way to do it instead of just manually inputting it? I have tried a loop but I just can't figure out how to make it work.
This should do the trick:
accounts = 100.times.collect { BankAccount.new(100) }
If you need to do something different for each account based on which one it is then:
accounts = 100.times.collect { |i| BankAccount.new(i) }
i represents each number in the collection being iterated over.
If you actually need to set the variable names using the data you can call eval().
accounts = 100.times.collect { |i| eval("B#{i} = BankAccount.new(100)") }
And now B1 through B100 should be set to the appropriate BankAccount instances.
Disclaimer:
I should say that this approach will be generally frowned upon. In this case you already have an array called accounts. All you need to do is index on it to get the corresponding bank account. accounts[50] for example instead of Ba50. In my years of ruby development I've found few places to use eval that made sense.
Related
With Puppet, in a custom ruby function is it possible to cache a value for a single catalog run?
I have this function:
Puppet::Functions.create_function(:myFunction) do
def myFunction( *arguments )
data = call_function( 'lookup', [ 'myHieraKey', nil, nil, {} ] )
data.length()
end
end
The function is called multiple times and would be more optimal if each invocation didn't query hiera.
I can't seem to find any hints as to how to do this. A quick and dirty way could be to define a unique class variable, however this pollutes one of the Puppet classes.
##mymodule_myfunction_myvariable = {}
Is there a "proper" way?
This method works, but I'm sure the performance could be greatly improved. Also, I'm realizing how fun and awesome it is to take smelly code like this, and rubify it. But I need a little more help to get my Ruby skills to the level to refactor something like this.
An objective can have "preassign" objectives. These are pre-requisites that must be completed before the a student can try the objective in question.
ObjectiveStudent is the join model between an objective and a student. It has a method called "points_all_time" that finds the student's best score on that objective.
The check_if_ready method is the one that I'm trying to refactor in this question. It also belong to the ObjectiveStudent model.
It needs to check whether the student has passed ALL of the preassigns for a given objective. If so, return true. Return false if the student has a less-than-passing score on any of the preassigns.
def check_if_ready
self.objective.preassigns.each do |preassign|
obj_stud = self.user.objective_students.find_by(objective_id: preassign.id)
return false if obj_stud.points_all_time < 7
end
return true
end
Right now I suspect this method is making too many calls to the database. What I'm really hoping to find is some way to look at the scores for the pre-reqs with a single db call.
Thank you in advance for any insight.
The following should work for you:
def is_ready?
user.objective_students
.where(objective_id: objective.preassigns.select(:id))
.none? { |obj_stud| obj_stud.points_all_time < 7 }
end
We collect all the objective_students for the user where the objective_id is in the list of objective.preassigns ids. This results in one 1 query being executed.
Then we use Enumerable#none? to make sure that none of the objective_students have points_all_time less than 7.
You could also use the inverse .all? { |obj_stud| obj_stud.points_all_time >= 7 } if you wanted
One way you could "rubify" this method is to rewrite the signature as:
def is_ready?
It is common practice to append ? to functions that return a boolean value in Ruby. (Note: I also don't really see a reason to have the word 'check' in the declaration, but that's just an opinion).
Furthermore, if objective_id is the primary key for the objective_students model, you can simply write objective_students.find(preassign.id) instead of the find_by method.
I would also suggest having a separate method for returning a student's points (especially since I suspect you will need to get a student's points more than just once) :
def getPoints(preAssignId)
return self.user.objective_students.find_by(objective_id: preAssignId).points_all_time
end
Then your main method can be written in a more clear, self-describing manner as:
def is_ready?
self.objective.preassigns.each {|preassign| return false if getPoints(preassign) < 7 }
return true
end
I am working with python and sqlalchemy. I have one table named Team and another named Game. The Game table has columns "away_id" and "home_id" and the Team table has the column "team_id". I just made this hybrid_method for the Team class which will return all game instances where the away_id, or home_id matches the team_id. The argument I pass it, s, is a session instance. How can I write this code as a #hybrid_property where I don't have to pass it a session instance?
#hybrid_method
def games(self, s):
return s.query(Game).filter(or_(Game.away_id==self.team_id, Game.home_id==self.team_id)).all()
First off, from what I can see here this is not a use case for "#hybrid" hybrid is used for specifically the use case where you'd like to say: "MyClass.games == something", at the class level, as well as, "my_object.games == something", at the instance level. That is not the case here, you're trying to run a query in its entirety, passing a specific self.team_id into it - so you need a self, so this is just a regular method or descriptor.
So just use #property with object_session() as the docs say right here:
class MyClass(Base):
# ...
#property
return object_session(self).query(Game).filter(...)
I'd like to know if I can add something similar to this in my class and have it build a class attribute that I can reference in other classes. I don't want to have to remember id's and I don't want to keep having to update id's as the id's in the weight tables change. Nor do I want to lock the weight table into a set of specific id's.
So I'd love to do something like the following:
class Weight < ActiveRecord::Base
attr_accessible :name
##kind = {
Weight.all.each do |weight|
weight.name.delete(' ').underscore.to_sym: weight.id,
end
}
cattr_reader :kind, :instance_accessor => false
end
Then in other areas of the code I can do things like..
scope :light, where(weight_id, Weight::kind(:light))
I'm sure there's some magic ruby way, I'm just not sure of the right syntax.
This is the closest I've come so far.
def self.kinds
kinds = Weight.all.map { |weight| { weight.name.delete(' ').underscore.to_sym => weight.id } }
kinds.reduce({}, :update)
end
and then...
scope :light, where(weight_id, Weight.kinds[:light])
Why not turn kind accessor into a class method which would lazily load the weights from database and lookup the neccessary one?
However, the stuff you are trying to do doesn't seem really good. What is the table behind Weight changes? What your classes will be loaded prior to the database connection gets set up (in some test environment, for instance)? I would suggest rewriting the scope to inner joing weight model with the appropriate name...
I've been practicing some Ruby meta-programming recently, and was wondering about assigning anonymous classes to constants.
In Ruby, it is possible to create an anonymous class as follows:
anonymous_class = Class.new # => #<Class:0x007f9c5afb21d0>
New instances of this class can be created:
an_instance = anonymous_class.new # => #<#<Class:0x007f9c5afb21d0>:0x007f9c5afb0330>
Now, when the anonymous class is assigned to a constant, the class now has a proper name:
Foo = anonymous_class # => Foo
And the previously created instance is now also an instance of that class:
an_instance # => #<Foo:0x007f9c5afb0330>
My question: Is there a hook method for the moment when an anonymous class is assigned to a constant?
There are many hooks methods in Ruby, but I couldn't find this one.
Let's take a look at how constant assignment works internally. The code that follows is extracted from a source tarball of ruby-1.9.3-p0. First we look at the definition of the VM instruction setconstant (which is used to assign constants):
# /insns.def, line 239
DEFINE_INSN
setconstant
(ID id)
(VALUE val, VALUE cbase)
()
{
vm_check_if_namespace(cbase);
rb_const_set(cbase, id, val);
INC_VM_STATE_VERSION();
}
No chance to place a hook in vm_check_if_namespace or INC_VM_STATE_VERSION here. So we look at rb_const_set (variable.c:1886), the function that is called everytime a constant is assigned:
# /variable.c, line 1886
void
rb_const_set(VALUE klass, ID id, VALUE val)
{
rb_const_entry_t *ce;
VALUE visibility = CONST_PUBLIC;
# ...
check_before_mod_set(klass, id, val, "constant");
if (!RCLASS_CONST_TBL(klass)) {
RCLASS_CONST_TBL(klass) = st_init_numtable();
}
else {
# [snip], won't be called on first assignment
}
rb_vm_change_state();
ce = ALLOC(rb_const_entry_t);
ce->flag = (rb_const_flag_t)visibility;
ce->value = val;
st_insert(RCLASS_CONST_TBL(klass), (st_data_t)id, (st_data_t)ce);
}
I removed all the code that was not even called the first time a constant was assigned inside a module. I then looked into all the functions called by this one and didn't find a single point where we could place a hook from Ruby code. This means the hard truth is, unless I missed something, that there is no way to hook a constant assignment (at least in MRI).
Update
To clarify: The anonymous class does not magically get a new name as soon as it is assigned (as noted correctly in Andrew's answer). Rather, the constant name along with the object ID of the class is stored in Ruby's internal constant lookup table. If, after that, the name of the class is requested, it can now be resolved to a proper name (and not just Class:0xXXXXXXXX...).
So the best you can do to react to this assignment is to check the name of the class in a loop of a background worker thread until it is non-nil (which is a huge waste of resources, IMHO).
Anonymous classes don't actually get their name when they're assigned to a constant. They actually get it when they're next asked what their name is.
I'll try to find a reference for this. Edit: Can't find one, sorry.