Jump to content

Some Random Programming Ideas


AtomicMaster

Recommended Posts

So when i try to solve problems, i sometimes come up with some pretty neat ideas about how to best express or contain something, that often turns ugly code somewhat more elegant, and i like elegant code :)

 

So I want share some random programming ideas, in random languages, perhaps some solutions. And you are also welcome to join me, perhaps this may help someone perhaps.

 

Here's an example:

 

This is something i have come up with a couple of years ago. It works when you need to have actions on data, perhaps called at random, or perhaps called every time, but you don't care what those actions are specifically (and they can be easily written or extended by someone else). All you care about is keeping track of some conditions that satisfy those actions (for example, i want to define actions ran at different time intervals, or i want to define action to act on string data, and other actions (or set their-of) to act on numerics). This is useful when you don't care which actions or what order the actions are executed, just that they are. You also get the benefit of a common ds, so you can keep track of data for all actions internally inside the structure.

require 'singleton'

class Legos
	include Singleton

	def initialize
		#you could initialize a common piece of data that the blocks act on here if you so chose
	end

	def blocks(id=1)
		@blocks ||= {}
		@blocks[id] ||= []
	end

	def blocks=(data, id=1)
		@blocks[id].push(data)
	end

	# Magic happens here
	def block(id=1, &block)
		raise "Windmills do not work that way! Good NIGHT." unless block_given?
		self.blocks(id) << block
	end

	# Main poll loop
	def build()
		 @blocks.each_key { |key|
			@blocks[key].each { |block|
			 	instance_exec(&block)
			}
		}
	end

end

castle = Legos.instance

castle.block() {
	puts 'One Block'
}

castle.block() {
	puts 'Two Block'
}

castle.block() {
	puts 'Three Block'
}

# So you can identify block types for example (you can extend it to have more than one attribute)
castle.block(2) {
	puts 'Four Block (out of order)'
}

castle.block() {
	puts 'Five Block'
}

castle.build
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.