Class and Method

XinChao

Veteran
Veteran
Joined
Jun 11, 2012
Messages
117
Reaction score
3
Primarily Uses
Ok, here is the code which is very confuse to me.

class Diedef roll

1 + rand(6)

end

end

dice = [Die.new, Die.new]

dice.each do |die|

puts die.roll

end
So, you have the class Die. Inside the class you have method roll.

Then you create an array with two Die class as values.

Then you use each method and do loop to print out the the values.

Which confuse me is when you create and empty class Die.new, it should have the method roll in it right?

Why would you need to create a class? you could have just create an empty variables.

Example

dice = [var1, var2]

dice.each do |die|

puts die.roll

end

Do you need to call the method roll for die.roll if the class Die already have the roll method in it?
 

TDS

- T D S -
Veteran
Joined
Mar 5, 2012
Messages
361
Reaction score
130
First Language
English
Primarily Uses
It looks like you want a module, not a class.



Code:
module Die
  def self.roll
    1 + rand(6)
  end
end
puts Die.roll
 

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,564
Reaction score
3,846
First Language
English
Do you need to call the method roll for die.roll if the class Die already have the roll method in it?
I don't understand the question.

1. If you want to use a method then you have to call it. That is how you usually invoke a function in many high-level languages.

2. Each `die` in that block is an instance of the Die class, where the `roll` method is defined, so back to #1



Code:
dice.each do |die|
   die.roll
end
is you telling each die in dice to roll. Maybe you are not clear about the difference between defining a method and actually calling a method?

Why would you need to create a class? you could have just create an empty variables.Example

dice = [var1, var2]

dice.each do |die|

puts die.roll

end
Again, not sure what you are asking. If you don't define the Die class, or the roll method, how does Ruby know what a Die is and what it means to roll a die?

But if you're asking why you need to create Die objects and instead why not just toss in some arbitrary variables: How does ruby know that var1 and var2 are supposed to be instances of Die? In fact, var1 and var2 have not been defined, so you will only get a syntax error. Now if you said



Code:
var1 = Die.new
var2 = Die.new

dice = [var1, var2]

...
That would be valid, but then again, they are Die objects, so it's not THAT much different from saying



Code:
dice = [Die.new, Die.new]
except that now you have two different ways to reference a particular die.

It looks like you want a module, not a class.



Code:
module Die
  def self.roll
    1 + rand(6)
  end
end
puts Die.roll
There is no difference between what you're doing and me defining a class the same way



Code:
class Die
   def self.roll
      1 + rand(6)
   end
end
p Die.roll
If the die roll is intended to be treated as a static method, I'm not too sure whether a class or a module is most appropriate. RPG Maker has definitely decided to use modules for their battle manager and data manager though they could have just as easily replaced the word "module" with "class"

Except me using a class actually allows me to extend to support multiple battle systems in a single project easily, which seems more logical than using mixins.
 
Last edited by a moderator:

IceDragon

Elder Cookie Dragon
Veteran
Joined
Mar 8, 2012
Messages
73
Reaction score
63
First Language
English
Primarily Uses
N/A
adding a bit in there:

.new is a class method associated with well.. Classes.

It creates an instance of the class.

That code seems like a waste to be though, O: Its not very useful unless you can change the number of sides on the die. *points at original post*

Class Level



Code:
class Die
end
def Die.roll
  rand(6) + 1
end
Die.roll # => Class Method
OR



Code:
class Die
  def self.roll
    rand(6) + 1
  end
end
Die.roll # => Class Method
OR

This looks a bit clunky though



Code:
class Die
  class << self
    def roll
      rand(6) + 1
    end
  end
end
Instance Level



Code:
class Die
  def roll
    rand(6) + 1
  end
end
puts Die.new.roll
A more effective dice class would be!



Code:
class Die
  def self.roll sides=6
    rand(sides) + 1
  end
  # // Instance level
  def initialize sides=6
    @sides = 6
  end
  attr_reader :sides
  def sides= n
    @sides = n.to_i
  end
  def roll
    rand(@sides) + 1
  end
end

# // Create 3 new dies
dies = Array.new(3) do |i| Die.new i+3 end
p dies.collect &:roll # => [4,5,6] or something like that
# // Create 1 die, and fill the Array with 3 references to it
dies = Array.new(3,Die.new(7)) 
p dies.collect &:roll # => [7,7,7] assumming you where a lucky guy :3
But hey :3 There are plenty of ways to hack a class together.
 
Last edited by a moderator:

XinChao

Veteran
Veteran
Joined
Jun 11, 2012
Messages
117
Reaction score
3
Primarily Uses
The code sample I took from the book "Learn to Program". It is confusing that's why I brought it up here for clarification. The author did explain it but It is not clear enough for me.

So we have the class and then method inside the class. This code from IceDragon makes more sense to me.

We have two separate things, an empty class and a method. Then we put the class in action by call the method, Die.roll



Code:
class Die
end
def Die.roll
  rand(6) + 1
end
Die.roll # => Class Method
Can you explain line by line IceDragon? Thanks



Code:
class Die
  def self.roll sides=6
	    rand(sides) + 1
  end
  # // Instance level
  def initialize sides=6
	    @sides = 6
  end
  attr_reader :sides
  def sides= n
	    @sides = n.to_i
  end
  def roll
	    rand(@sides) + 1
  end
end
# // Create 3 new dies
dies = Array.new(3) do |i| Die.new i+3 end
p dies.collect &:roll # => [4,5,6] or something like that
# // Create 1 die, and fill the Array with 3 references to it
dies = Array.new(3,Die.new(7))
p dies.collect &:roll # => [7,7,7] assumming you where a lucky guy :3
 
Last edited by a moderator:

IceDragon

Elder Cookie Dragon
Veteran
Joined
Mar 8, 2012
Messages
73
Reaction score
63
First Language
English
Primarily Uses
N/A
Just a little heads up:

Ruby returns the last evaluated line in a function/method by default so:



Code:
def my_x
  13
  return 14
  12
end
my_x # => 14
def my_y
  16
  17
end
my_y # => 17
Here we go, lets start with the first:



Code:
class Die
end
def Die.roll
  rand(6) + 1
end
Die.roll # => Class Method
Is the same as



Code:
class Die
  def self.roll
    rand(6) + 1
  end
end

Die.roll # => Class Method
How?

when you use the class keyword, you open the class for editing (therefore entering its scope)

Within the classes scope, self refers to the class object (Die in this case).

So:



Code:
module Die
  p self # => Die
end
p Die # => Die
Now for the keyword def:



Code:
def Die.roll
  rand(6) + 1
end

module Die
  def self.roll
    rand(6) + 1
  end
end
So essentially your saying: "define Die's roll function as"

And then we call the class function/method



Code:
Die.roll
die_module = Die # => Die
die_module.roll


Code:
class Die
  def self.roll sides=6
    rand(sides) + 1
  end
  # // Instance level
  def initialize sides=6
    @sides = sides
  end
  attr_reader :sides
  def sides= n
    @sides = n.to_i
  end
  def roll
    rand(@sides) + 1
  end
end
# // Create 3 new dies
dies = Array.new(3) do |i| Die.new i+3 end
p dies.collect &:roll           # => [4,5,6] or something like that
# // Create 1 die, and fill the Array with 3 references to it
dies = Array.new(3,Die.new(7))
p dies.collect &:roll           # => [7,7,7] assumming you where a lucky guy :3
Die.roll 7                      # => 3
I actually made a few mistakes in the code

Anyway:

Classes and Modules are 1 of the same.



Code:
class Die
  def self.roll(sides=6)
    rand(sides) + 1
  end
end
Die.roll 7 # => 5
In this case we have the class method roll for Die

That way we can make use of a roll function, without having to create an instance

of the class.

So what if we needed a portable dice or even multiple dies with different sides?

This is where the class comes in handy.



Code:
class Die
  # // Instance level
  def initialize sides=6
    @sides = 6
  end
  attr_reader :sides
  def sides= n
    @sides = n.to_i
  end
  def roll
    rand(@sides) + 1
  end
end
die = Die.new 9
die.roll # => 6
die.roll # => 3
die.roll # => 8
die.roll # => 1
But lemme expand on that:



Code:
my_die_set = [Die.new(4),Die.new(6),Die.new(16)]
So here I have 3 different dies: 4 sided, 6 sided and 16 sided respectively

I can now move around with my dies and play D&D probably.

Anyway continuing, I believe you covered attributes, but here is a quick rundown:



Code:
# // The attr* trio
attr_reader :x
# // is the same as
def x
  return @x
end

attr_writer :x
# // is the same as
def x= n
  @x = n
end

attr_accessor :x
# // is the same as
attr_writer :x
attr_reader :x
continuing on: I shouldn't have used the Array as apart of the example ;)



Code:
# // Create 3 new dies
dies = Array.new(3) do |i| Die.new i+3 end
p dies.collect &:roll           # => [4,5,6] or something like that
# // Create 1 die, and fill the Array with 3 references to it
dies = Array.new(3,Die.new(7))
p dies.collect &:roll           # => [7,7,7] assumming you where a lucky guy :3
Die.roll 7                      # => 3
Ignoring the comments:



Code:
dies = Array.new(3) do |i| Die.new i+3 end
p dies.collect &:roll           
dies = Array.new(3,Die.new(7))
p dies.collect &:roll           
Die.roll 7
Simplified:



Code:
dies = []
dies.push Die.new 1+3
dies.push Die.new 2+3
dies.push Die.new 3+3
results = dies.collect do |die| die.roll end
p results

dies = []
die = Die.new 7
dies.push die
dies.push die
dies.push die
results = dies.collect do |die| die.roll end
p results

Die.roll 7
Dont try to wrap your head around arrays yet, just remember, they are a collection

of objects in series.

push adds an object to the end of the array

unshift adds an object to the beginning of the array

pop removes and returns the last object in the array

shift removes and returns the first object in the array

collect is an Enumerable method that iterates through the array and collects the result as a new one

If your still not clear on something :3 I'll try to help.
 
Last edited by a moderator:

XinChao

Veteran
Veteran
Joined
Jun 11, 2012
Messages
117
Reaction score
3
Primarily Uses
I don't have problem with Array nor Hash.

What I did not understand before is the "return" below, but now I do. Thank you for the samples. The last line will have to return a value?



Code:
def my_x
  13
  return 14
  12
end
my_x # => 14
def my_y
  16
  17
end
my_y # => 17
If I have this code

def test1

if 12>13 end

end

what will it return? a false or a nil?

And this code what will it return

def test 2

number = 5

number2 =6

return number + number 2

number/number 2

end

========

Thank you, it clear up a little bit but still not I could understand. Can you give me another example about making a game. For example, create a character with health and mana.
 

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,564
Reaction score
3,846
First Language
English
I don't know what they would return, but you can always plug them into a ruby interpreter and check

http://ideone.com/vZwOe your 12 > 13 question. Guess ruby doesn't even accept it.

Revised: http://ideone.com/XIKQC. Makes sense, as it is the last line of execution within that method.

If a method reaches a return call, it will return whatever is on that line and ignore anything else inside that method.

Also, I would never say that classes and modules are the same thing. That is misleading.

For one, you cannot instantiate an instance of a module, and unlike classes, you can include modules in any class you want (mix-ins)

While at certain times they may function the same way, that's only because the author decided to write that particular snippet of code.
 
Last edited by a moderator:

IceDragon

Elder Cookie Dragon
Veteran
Joined
Mar 8, 2012
Messages
73
Reaction score
63
First Language
English
Primarily Uses
N/A
herp derp.

I didnt say they where the same, I said they where "1 of the same" O:

since Module is the parent of Class

But lets not get into the nitty gritty details D:

Adding to what you said however:

You cannot mix-in classes, but you can inherit from them.

Fun fun (include)



Code:
module MixinThing
  def cookies
    "chocolate!"
  end
end
class Factory
  def produce
    puts product
  end
  def product
    '-nothing here but us chickens-'
  end
end
class CookieFactory < Factory
  include MixinThing
  def product
    cookies!
  end
end
Factory.new.produce # => -nothing here but us chickens-
CookieFactory.new.produce # => chocolate!
MOAR FUN!! (extend)



Code:
class SomeFactory
  extend MixinThing
end
SomeFactory.cookies! # => chocolate!
 

XinChao

Veteran
Veteran
Joined
Jun 11, 2012
Messages
117
Reaction score
3
Primarily Uses
couple questions

first, initialize, i don't understand why do we need initialize.

second this code



Code:
Class Superdog
def feed (bones, fishes)
@bone = bones
#what if we do not create instance variable for the fish value, would it still display?
puts "feeding the dog #{bone} and #{fish}"
end
end
Try to run the code and I got error at "end"
 
Last edited by a moderator:

XinChao

Veteran
Veteran
Joined
Jun 11, 2012
Messages
117
Reaction score
3
Primarily Uses
For this class the output does not seem right.



Code:
class Thing				  

	  def initialize( aName, aDescription )		   
	    @name    = aName
	    @description  = aDescription
	  end

	  # get accessor for @name
	  def name
  return @name
	  end
	  # set accessor for @name
	  def name=( aName )
  @name = aName
	  end	 

	  # get accessor for @description
	  def description
  return @description
	  end
	  # set accessor for @description
	  def description=( aDescription )
  @description = aDescription
	  end	 


end	 
t = Thing.new("The Thing", "a lovely, glittery wotsit")
print( t.name )
print( " is " )
puts( t.description )
t.name = "A Refurbished Thing"
t.description = "a bit faded and worn around the edges"
print( "It has now changed its name to " )
puts( t.name )
print( "I would describe it as " )
puts( t.description )
The output has only 3 lines



Code:
The Thing is a lovely, glittery wotsit
It has now changed its name to A Refurbished Thing
I would describe it as a bit faded and worn around the edges
These two lines Ruby seems ignored them



Code:
print( " is " )
puts( t.description )
 

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,564
Reaction score
3,846
First Language
English
I don't think ruby ignored them, because otherwise they wouldn't appear in your output.
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts

How many parameters is 'too many'??
Yay, now back in action Happy Christmas time, coming back!






Back in action to develop the indie game that has been long overdue... Final Fallacy. A game that keeps on giving! The development never ends as the developer thinks to be the smart cookie by coming back and beginning by saying... "Oh bother, this indie game has been long overdue..." How could one resist such? No-one c
So I was playing with filters and this looked interesting...

Versus the normal look...

Kind of gives a very different feel. :LZSexcite:
To whom ever person or persons who re-did the DS/DS+ asset packs for MV (as in, they are all 48x48, and not just x2 the pixel scale) .... THANK-YOU!!!!!!!!! XwwwwX

Forum statistics

Threads
105,853
Messages
1,016,986
Members
137,561
Latest member
visploo100
Top