Jump to content

Some Random Programming Ideas

Featured Replies

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

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.