2

this is pretty crazy, and I feel really stupid asking this. But I have a basic code in Ruby and it's comprised of

  1. user input assigned to value
  2. input extracted to array by line
  3. iterations over each line extracting specific text and specific numbers
  4. if /else statements

    if text includes specific words then you apply math if text includes specific words you don't apply math

  5. i also have a running total that i assign outside the loop and add to inside the loop
this all works fine, but the project requires class structure, how do i take a code basically simple with if else statements basic loop (for each do |x|) and basic variable = true, or variable = input * 52/ 300

where do i start making this into class-based structure with OOP?

3
  • Does the project have any guidelines on how you should use classes? You could make a class (for instance) to hold the code that processes each line. A variable to hold the input and a method to iterate over each line. Commented Dec 13, 2013 at 21:38
  • Not really it just says show knowledge of object oriented programming and right now i have no classes in my script Commented Dec 13, 2013 at 21:48
  • production-quality, able to maintain/build on Commented Dec 13, 2013 at 21:53

1 Answer 1

1

I'll give you a basic outline to get your started, but I won't do your work for you. :)

First: define a class to hold your input.

class MyClass
  def initialize(data)
    @data = data
    ...put your initialization code here, this gets run when you call MyClass.new()
  end
  attr_accessor :data 
  ...
end

Second: define a "container" class to hold multiple instances of class.

class MyContainer
  def initialize(record)
    @records << record
  end
  ...
end

Third: for each line received, create a new instance of your class

mydata = MyClass.new(input)

Forth: store the new instance in your container class.

MyContainer.new(mydata)

Now, you can do things like create an add method in MyContainer which will iterate though all the classes it's holding in @records and produce a sum.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much! I'm just starting with ruby, so any help is much appreciated!
Sure thing, be sure to mark this as answered if you don't mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.