ruby 这几行swift代码是什么意思思呢?

ruby的一段代码$1,$2……这些是什么意思呢?菜鸟求教啊!_百度知道
ruby的一段代码$1,$2……这些是什么意思呢?菜鸟求教啊!
def han2num(string)
digit4 = digit3 = digit2 = digit1 = &0&
nstring = string.dup
nstring.gsub!(/一/, &1&)
nstring.gsub!(/二/, &2&)
nstring.gsub!(/三/, &3&)
nstring.gsub!(/四/, &4&)
nstring.gsub!(/五/, &5&)
nstring.gsub!(/六/, &6&)
nstring.gsub!(/七/, &7&)
nstring.gsub!(/八/, &8&)
nstring.gsub!(/九/, &9&)
if nstring =~ /((\d)?千)?((\d)?百)?((\d)?十)?(\d)?$/
digit4 = $2 || &1&
digit3 = $4 || &1&
digit2 = $6 || &1&
digit1 = $7 || &0&
return (digit4+digit3+digit2+digit1).to_iendp han2num(&七千八百二十三&)p han2num(&千八百二十三&)p han2num(&八百二十三&)p han2num(&百二十三&)p han2num(&百三&)p han2num(&二十三&)p han2num(&十三&)p han2num(&三&)
您的回答被采纳后将获得:
系统奖励20(财富值+经验值)+难题奖励30(财富值+经验值)
我有更好的答案
$1~$9是最后一次正则匹配的第一至第九个结果
这是什么用法,不太懂。。。。数字金额转换
为您推荐:
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁Ruby之代码块的迷思 - 我期望的世界 - ITeye技术网站
博客分类:
块的定义、调用与运行
在Ruby中,定义一个代码块的方式有2种 ,一是使用do … end, 另外一种是用大括号“{}”把代码内容括起来。代码块定义时也是可以接受参数的。但是,只有在调用一个方法的时候才可以定义一个块。
块定义好之后,会直接传递给调用的方法,在该方法中,使用“yield”关键字即可回调这个块。
def block_method(a, b)
a + yield(a, b)
puts block_method(1, 2) { |a, b| a*2+b } # =& 5
result = block_method(1, 2) do |a, b|
puts result
如果一个方法定义的时候使用了yield关键字,但是调用的时候却没有传递代码块,方法会抛出“no block given (yield) (LocalJumpError)”异常。可以使用Kernal#block_given?方法检测当前的方法调用是否包含代码块。
def check_block
return yield if block_given?
'no block'
puts check_block{ 'This is a block'}
# =& This is block
puts check_block
# =& no block
代码在运行的时候,除了需要代码外,还需要运行环境,即一组各种变量的绑定。代码块就是由代码和一组绑定组成的,代码块可以获得自己定义的局部变量的绑定,和上下文可见的实例变量,在代码块执行的时候,只会根据自己定义时可见的绑定来执行。业界把块这样的特性称之为闭包(Closure)。
def closure_method
x = "Goodbye"
yield("@xianlinbox")
x = "Hello"
puts closure_method { |y| "#{x} World, #{y}!" }
# =& Hello World, @xianlinbox!
作用域
前面提到代码运行时,需要一组绑定, 这组绑定在代码的运行过程中,还会发生变化,这种变化发生的根本原因就是作用域发生改变,每个变量绑定都有自己的作用域,一但代码切换作用域,旧的绑定就会被一批新的绑定取代。在Ruby的世界中,作用域相对简单,作用域之间是截然分开的,一旦进入另外一个作用域,原先的绑定就会替换为一组新的绑定,可以通过Kernal#local_variables方法查看当前作用域下的绑定。那么,程序什么时候会从一个作用域跳转到另一个作用域呢?
Ruby程序只会在3个地方关闭前一个作用域,同时打开一个新的作用域:
类定义, class … end
模块定义, module … end
方法定义, def … end
这三个地方通常称之为作用域们(Scope Gate)。
v1 = 1
class MyClass
puts local_variables.to_s + "call 1"
# =& [:v2]call 1
def my_method
puts local_variables.to_s + " call 2"
puts local_variables.to_s + "call 3"
# =& [:v2]call 3
obj = MyClass.new
obj.my_method
# =&[:v3] call 2
puts local_variables.to_s + "call 4"
# =&[:v1, :obj]call 4
因为作用域之间的隔离,让人忍不住会想,怎样才能让一个绑定穿越多个作用域?在Ruby中有一个叫做扁平化作用域(Flat Scope)的概念,通俗点说就是变身拆迁队长,拆掉所有的作用域门。
用Class.new()方法代替class关键字来定义类
使用Module。new()方法代替module关键字定义模块
使用Module#define_method代替def关键字定义方法。
MyClass = Class.new do
puts local_variables.to_s + "call 1"
# =& [:v2, :v1]call 1
define_method :my_method do
puts local_variables.to_s + " call 2"
puts local_variables.to_s + "call 3"
# =& [:v2, :v1]call 3
MyClass.new.my_method
# =& [:v3, :v2, :v1] call 2
puts local_variables.to_s + "call 4"
# =& [:v1]call 4
instance_eval()和instance_exec()
在Ruby中,提供了一个非常酷的特性,可以通过使用Objec#instance_eval(), Objec#instance_exec()方法插入一个代码块,做一个的对象上下文探针(Context Proble),深入到对象中的代码片段,对其进行操作。有了这个特性以后,就可以很轻松的测试对象的行为,查看对象的当前状态。
class MyClass
def initialize
obj = MyClass.new
obj.instance_eval do
# =& #&MyClass:0x007fbb2d0299b0&
obj.instance_exec(5) { |x| puts x * @v }
可调用对象
从底层来看,对代码块的使用分为2步,
* 打包代码备用
* 调用yiel执行代码
这种先打包,后执行的策略称之为延迟执行(Deferred Evaluation)。
代码块在Ruby中并不是一个对象,但是,如果你想把一个代码块保存为一个对象以供调用应该怎么办呢? Ruby提供了Proc类,其简单来说就是一个转换成对象的块。在Ruby中,把一个块转换为Proc对象的方法有以上4种:
* proc{…}
* Proc.new { …}
* lambda{…}
* &操作符
proc1 = proc { |x| x+1 }
puts proc1.class
proc2 = Proc.new { |x| x+1 }
puts proc2.class
proc3 = lambda { |x| x+1 }
puts proc3.class
&操作符只有在方法调用时才有效,在方法定义时,可以给方法添加一个特殊的参数,该参数必须为参数列表中的最后一个,且以&符号开头,其含义就是,这是一个Proc对象,我想把它当做一个块来用,如果调用该函数时,没有传递代码块,那么该参数值将为nil。有了这个符号之后,就可以很容易的把一个代码块转换为Proc对象,并在多个方法之间传递。
def my_method(&block)
test(&block)
puts yield(3) if block_given?
p2 = my_method{ |x| x+1 }
puts p2.class
Ruby中,所有的可调用对象,最后都是一个Proc对象,为什么还需要使用lambda这个方法来创建一个可调用对象呢? 使用lambda和使用proc创建的Proc对象有一些些微的差别,主要体现在2个方面:
return关键字的行为,lambda中,return仅表示从lambda中返回, 而proc中,则是从定义proc的作用域中返回。
参数校验规则:lambda中,参数个数不对,会抛ArgumentError错误,而proc中,则会尝试调整参数为自己期望的形式,参数多,则忽略多余的,参数少则,自动补nil。
def proc_method
p = proc { return 10 };
result = p.call
return result*2
def lambda_method
p = lambda { return 10 };
result = p.call
return result*2
puts proc_method
puts lambda_method
p1 = proc { |a, b| [a,b] }
p2 = lambda { |a, b| [a,b] }
puts p1.call(1, 2, 3).to_s
# =& [1, 2]
puts p1.call(1).to_s
# =& [1, nil]
puts p2.call(1, 2, 3).to_s
# =& ArgumentError
puts p2.call(1).to_s
# =& ArgumentError
ningandjin
浏览: 323887 次
来自: 成都
可以在网站()上试下在线表单方式 ...
也不给个例子,白看了
多谢,终于找到解决方案了
更新了,14年5.5.1版本
hobitton 写道看了文章,不知道dropwizard的优 ...ruby 代码的意思是什么?_百度知道
ruby 代码的意思是什么?
def make_sql(all_data, data_index)table_name = @table_name.downcase
sql = &select * from #{table_name} where &
1.upto(ARGV.length - 1) do |argv_index|
unless argv_index == 1
sql && & and &
sql && &#{all_data[0][ARGV[argv_index].to_i]} = #{all_data[data_index][ARGV[argv_index].to_i]}&
return sql这些代码是什么意思啊?
提问者采纳
这段代码是构建动态参数的数据库查询sql语句table_name是查询的表名然后根据ARGV也就是输入的所有参数,ARGV.length就是按照参数个数,一个循环也就是把输入的参数取出来,&#{all_data[0][ARGV[argv_index].to_i]} = #{all_data[data_index][ARGV[argv_index].to_i]}&上面的是根据输入的参数,构建查询的条件,一对一对的参数就是一个一个的条件看不懂的时候,把这些参数打印出来一个就知道什么意思了,总之,最后,是一个sql的查询语句return
提问者评价
来自团队:
其他类似问题
为您推荐:
您可能关注的推广回答者:
ruby的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁Ruby on Rails 入门之:(13) Ruby中的代码段传递调用
在Ruby中可以定义代码段,定义代码段的方式有两种,一种是使用 {} 定义一个代码段,一种是我们常用的do end方法。
代码块通常都是通过方法的调用来实现代码块中的功能。
在Ruby中,可以将一个代码块作为一个参数传递给方法,然后在方法中可以使用yield关键字调用传入的代码块。
#encoding:gbk&&
&&& puts &hello&;&
&&& puts &hi&;&
&&& puts &hahhhha&;&
#encoding:gbk
&puts &hello&;
&puts &hi&;
&puts &hahhhha&;
这里,在调用say函数的时候,给这个函数传递了一个代码段作为参数。并且在函数中使用yield调用了这个传递的代码段。
还可以在代码段中添加参数,然后在方法题中使用yield关键字调用代码段的时候传入参数。参数需要用|arg1,arg2|的格式声明。
#encoding:gbk&&
&&& puts &hello&;&
&&& yield &watkins&;&
&&& puts &hi&;&
say do |name|&
#encoding:gbk
&puts &hello&;
&yield &watkins&;
&puts &hi&;
say do |name|
代码段还可以返回参数,和一般的方法一样,代码块的返回值也是使用最后一个表示打的值,而且在方法中也可以使用和获取代码块的返回值。
#encoding:gbk&&
&&& puts &hello&;&
&&& puts yield &watkins&;&
&&& puts &hi&;&
say do |name|&
&&& &aaaaaaaaaaaaaaa&;&
#encoding:gbk
&puts &hello&;
&puts yield &watkins&;
&puts &hi&;
say do |name|
&&aaaaaaaaaaaaaaa&;让你的代码更有ruby风格 - 夜鸣猪的Ruby On Rails 空间 - ITeye技术网站
博客分类:
Quack Attack: Making Your Code More Rubyish
13:00, written by Gregory Brown
I’ve been doing some FFI work recently, which means that I’ve needed to wrap underlying C libraries so that I can call them from Ruby. While I won’t get into how the low level wrappers work, I can show you what the raw API calls look like for just a few functions:
view plaincopy to clipboardprint?
trip = API.PCMSNewTrip(server_id)
API.PCMSNumStops(trip)
API.PCMSAddStop(trip, string)
API.PCMSGetStop(trip, index, string_ptr, buffer_size)
API.PCMSDeleteStop(trip, index)
API.PCMSClearStop(trip)
All things considered, this looks pretty good for a direct wrapper on top of a C library. In fact, it’s relatively simple to mirror this to a more normalized Ruby layout. We can start by noticing that these calls are basically object oriented, focusing on the Trip object. While a Trip has other responsibilities, among them is managing a list of stops. With this in mind, we can flesh out a basic Trip object:
view plaincopy to clipboardprint?
class Trip
def initialize(server_id)
@server_id = server_id
@pointer = API.PCMSNewTrip(@server_id)
@stops = StopList.new(self)
attr_reader :stops
def call(*args)
API.send("PCMS#{args.first}",
@pointer, *args[1..-1])
The Trip#call helper removes some of the duplication for us, but it’ll be easier to see how it works in just a moment. For now, it’s worth pondering what a StopList should be.
If you look at the functions listed for dealing with stops, you’ll notice they map nicely to one of Ruby’s structures. We’re dealing with an ordered list of objects that can be added to and removed from. It can also be queried for its length, and deleted entirely. These features sure sound a lot like Ruby’s Array object, don’t they?
With this in mind, let’s do a quick experiment in interface design:
view plaincopy to clipboardprint?
class StopList
include Enumerable
def initialize(trip)
@trip = trip
def length
@trip.call :NumStops
def &&(loc)
@trip.call :AddStop, loc
def [](index)
ptr = FFI::MemoryPointer.new(:char, 100)
@trip.call :GetStop, index, ptr, 101
ptr.read_string
def delete_at(index)
@trip.call :DeleteStop, index
length.times do |i|
yield self[i]
@trip.call :ClearStops
Without paying too much attention to the implementation details, let’s take a look at what behaviors this new object supports:
view plaincopy to clipboardprint?
t = Trip.new(server_id)
t.stops && "New Haven, CT"
t.stops && "Naugatuck, CT"
t.stops && "Boston, MA"
p t.stops.length #=& 3
p t.stops[2] #=& "02205 Boston, MA, Suffolk"
t.stops.delete_at(1)
p t.stops[1] #=& "02205 Boston, MA, Suffolk"
p t.stops.map { |e| e.upcase } #=& [ "06511 NEW HAVEN, CT, NEW HAVEN",
"02205 BOSTON, MA, SUFFOLK" ]
t.stops.clear
p t.stops.length #=& 0
If this sort of interaction looks familiar to you, it’s because you’ve likely already done things like this thousands of times. But to make it blindingly obvious, let’s replace Trip#stops with an Array.
view plaincopy to clipboardprint?
stops = []
stops && "New Haven, CT"
stops && "Naugatuck, CT"
stops && "Boston, MA"
p stops.length #=& 3
p stops[2] #=& "Boston, MA"
stops.delete_at(1)
p stops[1] #=& "Boston, MA"
p stops.map { |e| e.upcase } #=& ["NEW HAVEN, CT", "BOSTON, MA"]
stops.clear
p stops.length #=& 0
You’ll notice that aside from lacking the location name normalization that our real code does implicitly, the key points we’ve highlighted have exactly the same behavior, using exactly the same interface. One benefit is immediately obvio the API for StopList doesn’t require you to learn anything new.
A more subtle gain that comes with this approach is that so long as it is restricted to the subset which StopList supports, code which expects an Array-like thing does not need to change, either.
For example, the following code will work just fine with either an Array or a StopList:
view plaincopy to clipboardprint?
def humanized(list)
list.each_with_index do |e,i|
puts "#{e} (#{i+1} / #{list.length})"
This makes things easier to test, and easier to be re-used for different purposes. Both are solid reasons for using this technique.
Of course, I’ve been glossing over a semi-major issue in the original code here, which I am sure has frustrated our more pedantic readers. The current StopList code, while quite useful, does not quack perfectly with Array. We needn’t look far for signs of divergence.
view plaincopy to clipboardprint?
p t.stops && "Chicago, IL" #=& 1
p t.stops.delete_at(2)
p t.stops.clear
These side-effect bearing functions are returning their C based values, which are different than what you’d expect from a Ruby Array. Luckily, each of these are easy to remedy.
In the case of the append operator (&&), we should return the StopList itself, to permit chaining:
view plaincopy to clipboardprint?
def &&(loc)
@trip.call :AddStop, loc
return self
To play nice with Array, our delete_at method should return the deleted object:
view plaincopy to clipboardprint?
def delete_at(index)
obj = self[index]
@trip.call :DeleteStop, index
return obj
Finally, since clear may also be chained, it should return the original object as well.
view plaincopy to clipboardprint?
@trip.call :ClearStops
return self
With these fixes in place, we can re-visit our previous example:
view plaincopy to clipboardprint?
p t.stops && "Chicago, IL" #=& #&Trip::StopList:0x0fcac ...&
p t.stops.delete_at(2)
#=& "60607 Chicago, IL, Cook"
p t.stops.clear
#=& #&Trip::StopList:0x0fcac ...&
There are probably some other minor details to catch, but now that our Array-ish StopList is “Good Enough For Government Work”, we have a nice stopping point. Let’s wrap things up with a little summary of things to remember.
Guidelines For Making Your Code More “Rubyish”
This is just one technique among many for improving your code, but I’d argue its a fairly important one. If you have a structure that mimics a subset of a core Ruby object’s capabilities, you can gain a lot by standardizing on a compatible interface. While sometimes the similarities end at the Enumerable and Comparable mixins, it’s reasonable to stretch things farther when it makes sense to do so. If you go that route (as we did here), there are just a few things to keep in mind:
&&& * You don’t need to implement every last feature of a core Ruby object in order to use this technique. So many functions rely on just a handful of available methods, that it makes sense to use this technique even when your problem domain is very small.
&&& * For the features you do implement, take care to maintain the same interface both on input and output. It’s fine to not support certain use cases, or to add extensions for new ones, but you should not diverge in the behaviors you do implement unless you have a good reason to.
&&& * Pay close attention to the return values of side-effect inducing functions, especially the ones mentioned in this article. Many Ruby methods are designed to be chainable, and breaking that feature can create a mess.
&&& * While this technique opens the door for using primitive objects for testing higher level functions, do not forget to adequately test the functionality of the actual objects you are implementing. Basically, make sure your code really quacks like a duck before substituting it with a duck somewhere else.
浏览: 1160534 次
user模型里加上
def email ...
shrekting 写道var pattern = /^(0| ...
好文章!!!
link_to其实就是个a标签,使用css控制,添加一个参数: ...
完全看不懂,不知所然.能表达清楚一点?}

我要回帖

更多关于 swift代码是什么意思 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信