Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Tutorial: Creating a simple class with methods


  • Please log in to reply
1 reply to this topic

#1 mr mike

mr mike

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 89 posts

Posted 03 January 2011 - 08:52 PM

Hello again. This is another basic tutorial in ruby. The goal in this tutorial is to create a class and define a few methods.

First we create the class
class Pizza
  def initialize(type = "peperoni pizza")
    @type = type
  def i_want
    %-"I want #{@type}!"-

  def i_dont_want
    %-"I dont want #{@type}!"-


The main thing to note is the methods in the class. They do not close with brackets, instead the close with "end"(as does the class). The reason for %-"I want #{@type}!"- is because I wanted the phrases in quotes. This eliminates having to use escape characters for quotes(ex. \"I want #{@type}\"").

Now lets get the program to use this class
p = Pizza.new("cheese pizza")
puts "John says, #{p.i_want}"
puts "Sue disagrees and says, #{p.i_dont_want}"

This code displays:
John says, "I want cheese pizza!"
Sue disagrees and says, "I dont want cheese pizza!"

Hope you enjoyed another one of these beginner tutorials. Ill wait for feedback before I post the next tutorial. I cannot decide if I want to show better examples of strings in ruby or continue with more class examples explaining strings as they appear. Any feedback is helpful, just remember these are beginner tutorials.

Edited by Roger, 06 January 2011 - 12:00 PM.

  • 0

#2 Lin Di

Lin Di

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 26 March 2012 - 12:36 AM

Hi mr mike,

Thanks for the tutorial. Could you explain a bit more regarding the syntax of "%- -"? Does it escape all special characters? Or does it work for the quotation marks only? I realize i am not able to find this use online.

Thank you.
  • 0

Also tagged with one or more of these keywords: ruby

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download