在Ruby中对字符串和block求解

http://tech.ddvip.com   2008年01月18日    社区交流

内容摘要:对包含代码的字符串和block求解,是我最钟爱的Ruby特性之一。Ruby提供了多种不同类型的求解方式;不过我最常用的是下面这些:eval、instance_eval和class_eval。

  第一个执行DSL的上下文被用来通知赌场雇员。代码如下:

class ContextOne < DslContext
bubble :than, :is, :list, :the, :to
def more(value)
'> ' + value.to_s
end
def method_missing(sym, *args)
@stakes = sym
eval "List.size_for(sym) #{args.first}"
end
def floor(value)
__position(value, :floor)
end
def brush(value)
__position(value, :brush)
end
def open
__action(:open)
end
def announce
__action(:announce)
end
def __action(to)
{ :action => to }
end
def __position(value, title)
value[:position] = title
value
end
def notify(value)
[@stakes, value]
end
end

  ContextOne通过下面的代码执行。

script = <<-eos
if the '$5-$10 Limit' list is more than 12 then notify the floor to open
if the '$1-$2 No Limit' list is more than 15 then notify the floor to open
if the '$5-$10 Limit' list is more than 8 then notify the brush to announce
if the '$1-$2 No Limit' list is more than 10 then notify the brush to announce eos
  
class Broadcast
def self.notify(stakes, options)
puts DslContext.sym_to_stakes(stakes)
options.each_pair do |name, value|
puts " #{name} #{value}"
end
end
end
ContextOne.execute(script) do |notification|
Broadcast.notify(*notification)
end

责编:豆豆技术应用

正在加载评论...