I have this class:
class Game
attr_accessor :player_fleet, :opponent_fleet
#player_fleet = []
#opponent_fleet = []
...
end
and create an instance like this:
my_game = Game.new
then use it like this:
my_game.opponent_fleet << opponent
which gives me this error:
undefined method `<<' for nil:NilClass (NoMethodError)
Why can't I treat an array like this? Do I have to create a method to push objects into the array?
You initialize #opponent_fleet at class level, so it's an instance variable of the class, not of the generated objects. Remember that in Ruby, even classes are objects :)
irb(main):001:0> class Game
irb(main):002:1> #foo = 3
irb(main):003:1> end
irb(main):004:0> Game.instance_eval { #foo }
=> 3
irb(main):005:0> Game.new.instance_eval { #foo }
=> nil
You want to initialize it in a constructor instead:
class Game
attr_accessor :player_fleet, :opponent_fleet
def initialize
#player_fleet = []
#opponent_fleet = []
end
end
Related
I am trying to access class methods within a define_singleton_method block, but it doesn't seem to be working.
Here is an example.
class Test
attr_accessor :tags
def initialize
#tags = []
#tags.define_singleton_method(:<<) do |val|
val = tosymbol(val)
push(val)
end
end
def tosymbol(value)
value = value.to_s
value = value.gsub!(/\s+/,'_') || value
value = value.downcase! || value
return value.to_sym
end
end
But when I use it I get an error.
test = Test.new
test.tags<<"Hello World"
NoMethodError: undefined method `tosymbol' for []:Array
from /home/joebloggs/GitHub/repo/file.rb:183:in `block in initialize'
from (irb):9
from /home/joebloggs/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'
I tried changing val = tosymbol(val) to val = Test::tosymbol(val) but that didn't work either, I get undefined method 'tosymbol' for Test:Class
I could re-write what tosymbol is doing, but it wouldn't be very DRY. Where am I going wrong? Thanks.
Where am I going wrong?
You're (re)defining a << method for instance of Array class, not Test class.
While doing so you are trying to access tosymbol method, that is not defined in Array class, but in Test class.
What you want, probably (read judging by your code sample), is to define << method for instances of Test class:
def initialize
#tags = []
end
def <<(val)
tags << tosymbol(val)
end
test = Test.new
test << "Hello World"
#=> [:hello_world]
EDIT
To make your example to work you just need to assign the instance to a variable and call the tosymbol method with correct receiver:
def initialize
#tags = []
test = self # <============
#tags.define_singleton_method(:<<) do |val|
val = test.tosymbol(val)
push(val)
end
end
Now:
test.tags << 'Hello World'
#=> [:hello_world]
class Numeric
##currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
def method_missing(method_id, *args, &block)
singular_currency = method_id.to_s.gsub(/s$/, '')
if ##currencies.has_key?(singular_currency)
self * ##currencies[singular_currency]
else
super
end
end
end
puts 3.yen
# Output is
# 0.039
My question is why wouldn't this code work if we replaced ##currencies with an instant variable #currencies and added attr_reader :currencies
Something like this
class Numeric
#currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
attr_accessor :currencies
def method_missing(method_id, *args, &block)
singular_currency = method_id.to_s.gsub(/s$/, '')
if #currencies.has_key?(singular_currency)
self * #currencies[singular_currency]
else
super
end
end
end
puts 3.yen
# Output
# method_missing': undefined method `has_key?' for nil:NilClass (NoMethodError)
# from Untitled.rb:15:in `<main>'
Isn't 3 already an instant of a class Numeric, therefore, the setter currencies should be able to work and return the proper hash combo?
EDIT: so method_missing is a static method then? Why isn't it defined with self.method_missing?
Setting #currencies within the context of a class declaration sets an instance variable on the class itself:
Numeric.instance_variable_get(:#currencies)
#=> {"yen"=>0.013, "euro"=>1.292, "rupee"=>0.019}
On the other hand, #currencies within the method_missing class and currencies accessor refers to the #currencies variable on a particular instance of numeric, which isn't defined:
Numeric.new.instance_variable_get(:#currencies)
#=> nil
You could fix this by defining the accessor on the class itself, and calling that accessor in the method_missing method:
class Numeric
#currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
class << self
attr_accessor :currencies
end
def method_missing(method_id, *args, &block)
singular_currency = method_id.to_s.gsub(/s$/, '')
if self.class.currencies.has_key?(singular_currency)
self * self.class.currencies[singular_currency]
else
super
end
end
end
Numeric.currencies
#=> {"yen"=>0.013, "euro"=>1.292, "rupee"=>0.019}
There's still a problem with this approach though. Even though the currencies accessor now refers to an instance variable on the class (and not an instance variable on a particular instance of that class as was the case before), #currencies is still only set on the Numeric class, not any of its subclasses:
Fixnum.currencies
#=> nil
To fix this, you can either modify the attribute accessor to automatically provide a default value for each individual class (so Fixnum and Float would each have their own separate #currencies variable), or go back to using class variables, like this:
class Numeric
##currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
def self.currencies
##currencies
end
def self.currencies= new_currencies
##currencies = new_currencies
end
def method_missing(method_id, *args, &block)
singular_currency = method_id.to_s.gsub(/s$/, '')
if ##currencies.has_key?(singular_currency)
self * ##currencies[singular_currency]
else
super
end
end
end
Numeric.currencies
#=> {"yen"=>0.013, "euro"=>1.292, "rupee"=>0.019}
Fixnum.currencies
#=> {"yen"=>0.013, "euro"=>1.292, "rupee"=>0.019}
1.yen
#=> 0.013
Numeric.currencies['bitcoin'] = 394.03
#=> 394.03
5.bitcoin
#=> 1970.1499999999999
You could do this:
class Numeric
#currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
class << self
attr_reader :currencies
end
def method_missing(method_id, *args, &block)
singular_currency = method_id.to_s.gsub(/s$/, '')
if Numeric.currencies.key?(singular_currency)
self * Numeric.currencies[singular_currency]
else
super
end
end
end
The lines:
class << self
attr_reader :currencies
end
create a read accessor for the class instance variable #currencies.
You may be inclined to write (as I did initially):
if self.class.currencies.key?(singular_currency)
but that doesn't work, because method_missing is invoked on 3, an instance of Fixnum, a subclass of Numeric. Recall that subclasses don't have direct access to their ancestor's class methods. That's why we need to explicitly identify Numeric as the receiver.
As:
Fixnum.ancestors => [Fixnum, Integer, Numeric,...]
we see that:
if self.class.superclass.superclass.currencies.key?(singular_currency)
would work with Fixnum's, but not with other subclasses of Numeric: Bignum and Float.
Instance variable are only available on instances of a class. Class variables are available to the entire class.
In other words, the #currencies.has_key? in your code is undefined because it can't see the #currencies on line 2.
The problem is that you're initializing #currencies outside of a method. Any code that isn't inside a method is evaluated in the context of the class object, not an instance of the class.
Take a look at this example class:
class Foo
#bar = "baz"
def self.bar; #bar; end
def bar; #bar; end
end
Now let's look at the result of those two methods we defined.
Foo.bar # => "baz"
Foo.new.bar # => nil
This means that #bar belongs to the Foo class, not an instance of Foo.
Your problem can be solved by initializing #currency in a method, typically initialize:
class Numeric
def initialize
#currency = ...
end
end
I am doing the ruby koans and I am on the DiceSet project. I've made the DiceSet class but my instance variables don't seem to persist with the instance like I thought they would. My code is
class DiceSet
attr_reader :values
#values = []
puts #values.class
def roll(number_of_rolls)
(1..number_of_rolls).each do |roll|
puts #values.class
#values << (1..6).to_a.sample
end
return #values
end
end
The koan then uses my DiceSet class with
dice = DiceSet.new
dice.roll(5)
puts dice.values.class
assert dice.values.is?(Array)
I put the puts commands in there to follow whats happening with the #values instance variable and only the first puts #values.class says its an Array class. All the others are returning NilClass. Am I using instance variables incorrectly or is there something else I am missing? Do instance variables get deallocated after a method call?
EDIT: My class works correctly now that I have put #values = [] in the roll method as suggested below. My only question now, is why the roll method thinks that #values is a NilClass instead of an array when I put #values = [] in an initialize method
In Ruby everything are objects. The Ruby interpreter assumes that all instance variables belong to the current object self. This is also true in a class definition. The role of self belongs to the class itself, so the instance variable #values belongs to the class. Don’t get confused! Instance variables of the class are different from instance
variables of that class’s objects. Also you don't need specify return keyword explicitly Try this:
class DiceSet
attr_accessor :values
def roll(number_of_rolls)
#values = []
(1..number_of_rolls).each do |roll|
#values << (1..6).to_a.sample
end
#values
end
end
dice = DiceSet.new
dice.roll(5)
puts dice.values.class
assert dice.values.is_a?(Array)
Each DiceSet instance has its own #values, and furthermore, the class DiceSet also has its own #values. They are all different from one another. If you want the instances and the class to share the same variable, you should use a class variable ##values.
Just put the declaration of #values = [] in the initialized method and your code should work as expected.
class DiceSet
attr_reader :values
def initialize()
#values = []
end
def roll(number_of_rolls)
(1..number_of_rolls).each do |roll|
puts #values.class
#values << (1..6).to_a.sample
end
return #values
end
end
Try this:
class Cat
attr_accessor :age
def initialize
#age = 12
end
#age = 6
def meow
puts "I'm #{#age}"
end
def self.meow
puts "I'm #{#age}, going on #{#age+1}"
end
end
Cat.age = 4 # => NoMethodError: undefined method `age=' for Cat:Class
p Cat.age # =? NoMethodError: undefined method `age' for Cat:Class
Cat.meow # => I'm 6, going on 7
cat = Cat.new
p cat.age # => 12
cat.meow # => I'm 12
cat.age = 20 # => 20
cat.meow # => I'm 20
Were I to add
class << self
attr_accessor :age
end
the first three lines of output would become:
Cat.age = 4 # => 4
p Cat.age # => 4
Cat.meow # => I'm 4, going on 5
class A
##ololo = 1
end
A::ololo
A.new.ololo
NoMethodError: undefined method `ololo'
okey. I need an attr_reader
class B
##ololo = 1
attr_reader :ololo
end
A::ololo
NoMethodError: undefined method `ololo'
A.new.ololo
=> nil
wtf? is there any limit for ruby accessors?
class C
##ololo = 1
def self.ololo
##ololo
end
def ololo
##ololo
end
end
C::ololo
=> 1
C.new.ololo
=> 1
Ruby men usually say "yeah! pretty good!". is this pretty good?
Can anyone provide shorter code?
You can't do what you want to do :)
#harald is right. attr_reader will define GETTER only for instance variable, for "static" (aka "class variables") you need to define setter and getter by yourself:
class A
##ololo = 1
# instance level
# getter
def ololo
##ololo
end
# setter
def ololo=trololo
##ololo = trololo
end
# and class level
# if you need it
# getter
def self.ololo
##ololo
end
# setter
def self.ololo=trololo
##ololo = trololo
end
end
So:
a = A.new
b = A.new
A.ololo
#=> 1
a.ololo
#=> 1
A.ololo = 100
A.ololo
#=> 100
a.ololo
#=> 100
b.ololo
#=> 100
a.ololo = 4
A.ololo
#=> 4
...
Shorter one:
class A
#ololo = 1
class << self
attr_accessor :ololo
end
end
attr_accessor :ololo defines the methods ololo and ololo= which work against an instance variable named #ololo. So what happens when you try to access A::ololo ruby will find your instance method ololo and fail since you're trying to call it as a class method.
Yes, you can.
class A
cattr_accessor :ololo
##ololo = 1
end
class B
A.ololo #Gets class variable "ololo" from class A
end
This is basically a Ruby on Rails feature. However, outside Rails, you can obtain the functionality from the Ruby Facets gem:
https://github.com/rubyworks/facets/blob/master/lib/core-uncommon/facets/module/cattr.rb
See this discussion:
cattr_accessor outside of rails
I have a Ruby class called LibraryItem. I want to associate with every instance of this class an array of attributes. This array is long and looks something like
['title', 'authors', 'location', ...]
Note that these attributes are not really supposed to be methods, just a list of attributes that a LibraryItem has.
Next, I want to make a subclass of LibraryItem called LibraryBook that has an array of attributes that includes all the attributes of LibraryItem but will also include many more.
Eventually I will want several subclasses of LibraryItem each with their own version of the array #attributes but each adding on to LibraryItem's #attributes (e.g., LibraryBook, LibraryDVD, LibraryMap, etc.).
So, here is my attempt:
class LibraryItem < Object
class << self; attr_accessor :attributes; end
#attributes = ['title', 'authors', 'location',]
end
class LibraryBook < LibraryItem
#attributes.push('ISBN', 'pages')
end
This does not work. I get the error
undefined method `push' for nil:NilClass
If it were to work, I would want something like this
puts LibraryItem.attributes
puts LibraryBook.attributes
to output
['title', 'authors', 'location']
['title', 'authors', 'location', 'ISBN', 'pages']
(Added 02-May-2010)
One solution to this is to make #attributes a simple instance variable and then add the new attributes for LibraryBoot in the initialize method (this was suggested by demas in one of the answers).
While this would certainly work (and is, in fact, what I have been doing all along), I am not happy with this as it is sub-optimal: why should these unchanging arrays be constructed every time an object is created?
What I really want is to have class variables that can inherit from a parent class but when changed in the child class do not change in the the parent class.
Another solution would be to use the inherited hook:
class LibraryItem < Object
class << self
attr_accessor :attributes
def inherit_attributes(attrs)
#attributes ||= []
#attributes.concat attrs
end
def inherited(sublass)
sublass.inherit_attributes(#attributes)
end
end
#attributes = ['title', 'authors', 'location',]
end
class LibraryBook < LibraryItem
#attributes.push('ISBN', 'pages')
end
Since you mention that the attributes are "fixed" and "unchanging", I am assuming that you mean that you will never change their value once the object is created. In that case, something like the following should work:
class Foo
ATTRS = ['title', 'authors', 'location']
def attributes
ATTRS
end
end
class Bar < Foo
ATTRS = ['ISBN', 'pages']
def attributes
super + ATTRS
end
end
You are manually implementing a reader method (instead of letting attr_accessor create it for you) that disguises the internal name of the array. In your subclass, you simply call the ancestor class' reader function, tack on the additional fields associated with the child class, and return that to the caller. To the user, this appears like a read-only member variable named attributes that has additional values in the sub-class.
Just as a version:
class LibraryItem < Object
def initialize
#attributes = ['one', 'two'];
end
end
class LibraryBook < LibraryItem
def initialize
super
#attributes.push('three')
end
end
b = LibraryBook.new
Out of curiosity, will something like this work?
class Foo
ATTRIBUTES = ['title','authors','location']
end
class Bar < Foo
ATTRIBUTES |= ['ISBN', 'pages']
end
This would seem to produce the desired result - the ATTRIBUTES array is expanded when the class object is created, and the values of ATTRIBUTES varies as expected:
> Foo::ATTRIBUTES
=> ['title','authors','location']
> Bar::ATTRIBUTES
=> ['title','authors','location', 'ISBN', 'pages']
To expand on #Nick Vanderbilt's answer, using active_support you do this, which is exactly the short hand I want for this functionality. Here's a complete example:
require 'active_support/core_ext'
class Foo
class_attribute :attributes
self.attributes = ['title','authors','location']
end
class Bar < Foo
self.attributes = Foo.attributes + ['ISBN', 'pages']
end
puts Foo.attributes.inspect #=> ["title", "authors", "location"]
puts Bar.attributes.inspect #=> ["title", "authors", "location", "ISBN", "pages"]
Shame it's so difficult for ruby to achieve this without needing a library for it. It's the only thing I miss from python. And in my case, I don't mind the dependency on the active_support gem.
ActiveSupport has class_attribute method in rails edge.
In LibraryBook variable #attributes is a new independent variable, instance variable of object LibraryBook, so its not initialized and you get error "undefined method ... for nil"
You should to initialize it by LibraryItem attribut's list before using
class LibraryBook < LibraryItem
#attributes = LibraryItem::attributes + ['ISBN', 'pages']
end
This is for strings (anything really), rather than arrays, but...
class A
def self.a
#a || superclass.a rescue nil
end
def self.a=(value)
#a = value
end
self.a = %w( apple banana chimp )
end
class B < A
end
class C < B
self.a += %w( dromedary elephant )
end
class D < A
self.a = %w( pi e golden_ratio )
end
irb(main):001:0> require 'test2'
=> true
irb(main):002:0> A.a
=> ["apple", "banana", "chimp"]
irb(main):003:0> B.a
=> ["apple", "banana", "chimp"]
irb(main):004:0> C.a
=> ["apple", "banana", "chimp", "dromedary", "elephant"]
irb(main):005:0> D.a
=> ["pi", "e", "golden_ratio"]
irb(main):006:0> A.a = %w( 7 )
=> ["7"]
irb(main):007:0> A.a
=> ["7"]
irb(main):008:0> B.a
=> ["7"]
irb(main):009:0> C.a = nil
=> nil
irb(main):010:0> C.a
=> ["7"]
You can do it using CONSTANTS also. No check though.
class LibraryItem < Object
class << self; attr_accessor :attributes; end
ATTRIBUTES = ['title', 'authors', 'location',]
end
class LibraryBook < LibraryItem
ATTRIBUTES .push('ISBN', 'pages']
end