Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Mar 26th, 2006, 11:11 AM   #1
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
Ruby Snippets

I learn best by picking apart other folks code samples. Does anyone know of a good repository of rudimentary Ruby snippets?
__________________
I looked it up on the Intergnats!
Dietrich is offline   Reply With Quote
Old Mar 26th, 2006, 2:35 PM   #2
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
Smile

If you are interested, there is a very nice and intelligent discussion (no flame-war) of "Ruby or Python" at:
http://forums.devshed.com/other-prog...on-333624.html
__________________
I looked it up on the Intergnats!
Dietrich is offline   Reply With Quote
Old Mar 26th, 2006, 2:58 PM   #3
Master
Programmer
 
Master's Avatar
 
Join Date: Sep 2005
Location: GA
Posts: 99
Rep Power: 4 Master is on a distinguished road
class Time
  def tenth
    time_time = ("%0.1f" % self)
    new_time = time_time.split(//)
    return (new_time[-2] + new_time[-1]).to_i
  end

  def hundth
    time_time = ("%0.2f" % self)
    new_time = time_time.split(//)
    return (new_time[-2] + new_time[-1]).to_i
  end
end

class Array
   def list=(array)
	self.clear
	array.each{|i| self << i}
   end
end  

  

class Object

  def encode(string)
    return if !string.is_a?(String)
    @str = string.unpack('B*')[0].tr('01', " \n")
  end
  def decode(string)
  return if !string.is_a?(String)
    [string.tr(" \n", '01')].pack('B*')
  end
   def deep_clone
     Marshal.load(Marshal.dump(self))
   end
   def get_param(param, type)
  args = nil
  case type
    when 0
      file = IO.readlines(__FILE__)
    else
      file = type
  end
  for i in 0...file.size
    if file[i].include?("def "+param)
      args = file[i].slice(file[i].index("(")+1..file[i].index(")")-1)
      break
    end
  end
  return "" if args.nil?
  return args.split(",")
end
 end
 class Array
   def count(item)
     num = 0
     self.each{|v| num += 1 if v == item}
     return num
   end
 end
class Object
  def If(bool, &block)
    if !bool
      return false
    end
    block.call
  end
  def For(var, bool, type, &block)
    while (bool != var)
      case type
        when "+"
          var += 1
        when "-"
          var -= 1
      end
      yield var
    end
  end
end
class Object
  def self.alias_class_method(new, old)
	new = new.to_s if new.is_a?(Symbol)
	old = old.to_s if old.is_a?(Symbol)
	raise ArgumentError.new('new and old must be a symbol or a string of the method name') unless new.is_a?(String) and old.is_a?(String)
	class_eval <<-EVALEND
	  def self.#{new}(*args)
		self.#{old}(*args)
	  end
	EVALEND
  end
end
#EXample
#=begin
For(m = 0, 5, "+") {|v|
 If(v == 2) {
  print "M = ", v,"\n" 
  break
  }
}

#=end
#EXample
Master is offline   Reply With Quote
Old Mar 27th, 2006, 4:01 PM   #4
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
Smile

Master thanks!

I am thinking more about simple code snippets you can use to learn the language with. I am not ready for the oops stuff yet! Like to see code like input data from the user or files, some math or string processing, arrays, searches, sorts, and output formatting. Also games, hangman would be nice, and perhaps simple GUI examples.
__________________
I looked it up on the Intergnats!
Dietrich is offline   Reply With Quote
Old Mar 27th, 2006, 4:17 PM   #5
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 646
Rep Power: 4 Jessehk is on a distinguished road
Here is a hangman game I wrote:

#!/usr/bin/ruby -w

# A hangman game
class Hangman
	def initialize(word)
		(@word = word).downcase!
		@progress = "_" * word.length
		@chances = 8
		@guessed = []
	end

	#Guess a letter in the secret word.
	#Hangman#progress will be modified to reflect the guessed letters.
	#Returns true if the letter is in the word, false otherwise
	#
	#params:
	#	letter => The letter being guessed -- a single character string
	#
	#exceptions:
	#	ArgumentError => if guess is not a single letter, or string
	def guess(letter)
		if letter.class.to_s != "String" or letter.length != 1
			raise ArgumentError, "Guess must be a single-character string!"
		else
			letter.downcase! #make sure letter is lower-case
			if @guessed.include? letter 
				raise ArgumentError, "Letter \"#{letter}\" was guessed already!"
			else
				@guessed << letter #add the letter to the list of guessed letters
				
				found = false
				(0...@word.length).zip(@word.scan(/\w/)) do |p, l| #enumerate each letter in the secret word
					if l == letter #if the letter matches...
						@progress[p] = l #...change @progress to reflect user's guess
						found = true #a match has been found
					end
				end
			end
			@chances -= 1 if !found #decrement the number of chances the user has left if a bad guess was made
			@guessed.sort!
			found #return true if a good guess, false otherwise
		end
	end

	#Check for a winner.
	#
	#Returns true if there is a winner, false otherwise.
	def winner?
		@progress == @word
	end

	#guessed letters.
	#
	#Returns a string of the previously guessed letters.
	def guessed
		@guessed.join(", ")
	end

	#Return the word as revealed by the player in a string. 
	#For example: "_ _ a _ _ t"
	def progress
		@progress.scan(/_|\w/).join(' ')
	end

	attr_reader :chances, :word
end

File.open("words.txt", 'r') do |f|
	words = []
	f.each { |w| words << w.gsub(/ /, '').chomp } #make sure word is free of spaces and trailing newline character removed
	
	h = Hangman.new(words[rand(words.length)]) #choose a random word
	
	while true
		begin
			break if h.winner? or h.chances < 0 #if the chances are up or there is a winner

			puts "\n#{h.progress.center(40)}"
			print "\n\nGuessed: ", h.guessed, "\n\n"
			puts "\nChances: #{h.chances}"
			print "\n\tEnter guess: "

			if h.guess(gets.chomp)
				puts "\nGreat guess!\n"
			else
				puts "\nOops! Bad guess.\n"
			end

			puts "______________________________"
			sleep 1

		rescue
			puts "\n#{$!}\n" #print error message
			sleep 2
			retry
		end
	end

	if h.chances > - 1
		puts "\nGreat game! You guessed the word \"#{h.word}\"!"
	else
		puts "\nNo chances left! The word was \"#{h.word}\". Better luck next time."
	end
end

I suggest you read this book ( http://ruby-doc.org/docs/ProgrammingRuby/ ), as there are plenty of snippets.
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Old Mar 27th, 2006, 4:27 PM   #6
Master
Programmer
 
Master's Avatar
 
Join Date: Sep 2005
Location: GA
Posts: 99
Rep Power: 4 Master is on a distinguished road
code snippet for a TreeNode
class Tree
	attr_accessor :root
	class Nodes
		attr_reader :data
		attr_reader :left
		attr_reader :right
		attr_reader :middle
		def initialize(data)	
			@data = data
			@right,@left,@middle = nil,nil,nil
		end
		
		def insert(value)
			if value < @data
				if @left.nil?
					@left = Nodes.new(value)
				else
					@left.insert(value)
				end
			elsif value > @data
				if @right.nil?
					@right = Nodes.new(value)
				else
					@right.insert(value)
				end
			#elsif value == @data
			#	if @middle.nil?
			#		@middle = Nodes.new(value)
			#	else
			#		@middle.insert(value)
			#	end
			end
		end
	end#End of Nodes
	
	def initialize()
		@root = nil
	end
	
	def insertNode(value)
		if @root.nil?
			@root = Nodes.new(value)
		else
			@root.insert(value)
		end
	end
	
	def preorder(node = @root)
		return if node.nil?
		print node.data, ", "
		preorder(node.left)
		#preorder(node.middle)#middle
		preorder(node.right)
	end
	
	def inorder(node = @root)
		return if node.nil?
		inorder(node.left)
		print node.data, ", "
		#inorder(node.middle)#middle
		inorder(node.right)
	end
	
	def postorder(node = @root)
		return if node.nil?
		postorder(node.left)
		postorder(node.right)
		#postorder(node.middle)#middle
		print node.data, ", "
	end
	
	def count(node = @root)
		count = 0
		return if node.nil?
		count += 1 if !node.left.nil? ||
		!node.right.nil? || !node.middle.nil?
		count(node)
		return count
	end
	
	def depth(node = @root)
		
	end
	
end#End of Tree
Master is offline   Reply With Quote
Old Mar 27th, 2006, 6:31 PM   #7
Kakao
Newbie
 
Join Date: Feb 2006
Posts: 9
Rep Power: 0 Kakao is on a distinguished road
Quote:
Originally Posted by Dietrich
I learn best by picking apart other folks code samples. Does anyone know of a good repository of rudimentary Ruby snippets?
Nice reading:
http://pleac.sourceforge.net/pleac_ruby/index.html

Python version:
http://pleac.sourceforge.net/pleac_python/index.html
Kakao is offline   Reply With Quote
Old Mar 27th, 2006, 6:57 PM   #8
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 646
Rep Power: 4 Jessehk is on a distinguished road
Wow, that's great. Thanks.
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Old Mar 27th, 2006, 7:54 PM   #9
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
Smile

Thanks Kakao!
Using the info from both, I am amazed this works:
# playing with multiline strings

str1 = <<"EOS"
This is a multiline text string
terminated by EOS on a line by itself
EOS

puts str1, "\n"

str2 = """Another
multiline
string
Python style"""

puts str2, "\n"

"""
Actually 
you can
use triple quotes
to make a 
multiline
comment in Ruby!
"""

# now it gets even simpler

str3 = "A 
simpler
multiline
string"

puts str3

"
Actually 
you can
use single quotes
to make a 
multiline
comment in Ruby!
"
My head is spinning!
__________________
I looked it up on the Intergnats!

Last edited by Dietrich; Mar 27th, 2006 at 8:12 PM.
Dietrich is offline   Reply With Quote
Old Apr 9th, 2006, 5:10 PM   #10
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 646
Rep Power: 4 Jessehk is on a distinguished road
This method will be available in version 1.9, but I wrote my own. I'm sure it could be done more efficiently somehow.

class Array
	def max_by(&block)
		elem, value = 0, 0

		each do |v|
			result = block.call(v)
			
			if result > value
				elem, value = v, result
			end
		end

		elem
	end
end

Example usage:

$ irb --simple-prompt
>> require 'max_by'
=> true
>> "Hello, my name is Jesse. Isn't that fantastic?".scan(/\w+/).max_by { |x| x.length }
=> "fantastic"
>>
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:28 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC