Ruby怎么将数组转换为函数参数

Python08

Ruby怎么将数组转换为函数参数,第1张

有3种方式,

1. 使用send方法

第一种实现动态方法调用是使用send方法,send方法在Object类中定义,方法的第一个参数是一个符号用来表示所要调用的方法,后面则是所调用方法需要的参数。

“This is a dog1″.send(:length) =>14

上面的代码中通过send方法去对一个字符串执行length操作,返回字符串的长度。

class TestClass

def hello(*args)

”Hello ” + args.join(‘ ‘)

end

end

a = TestClass.new

puts a.send :hello, “This”, “is”, “a”, “dog!”

执行结果为:

Hello This is a dog!

2. 使用Method类和UnboundMethod类

另一种实现动态方法调用是使用Object类的method方法,这个方法返回一个Method类的对象。我们可以使用call方法来执行方法调用。

test1 = “This is a dog1″.method(:length)

test1.call =>14

class Test

def initialize(var)

@var = var

end

def hello()

”Hello, @var = #{@var}”

end

end

k = Test.new(10)

m = k.method(:hello)

m.call #=>“Hello, @iv = 99″

l = Test.new(‘Grant’)

m = l.method(“hello”)

m.call #=>“Hello, @iv = Fred”

可以在使用对象的任何地方使用method对象,当调用call方法时,参数所指明的方法会被执行,这种行为有些像C语言中的函数指针。你也可以把method对象作为一个迭代器使用。

def square(a)

a*a

end

mObj = method(:square)

[1, 2, 3, 4].collect(&mObj) => [1 4 9 16]

Method对象都是和某一特定对象绑定的,也就是说你需要通过某一对象使用Method对象。你也可以通过UnboundMethod类创建对象,然后再把它绑定到某个具体的对象中。如果UnboundMethod对象调用时尚未绑定,则会引发异常。

class Double

def get_value

2 * @side

end

def initialize(side)

@side = side

end

end

a = Double.instance_method(:get_value) #返回一个UnboundMethod对象

s = Double.new(50)

b = a.bind(s)

puts b.call

执行结果为:

100

看下面一个更具体的例子:

class CommandInterpreter

def do_2() print “This is 2\n”end

def do_1() print “This is 1\n”end

def do_4() print “This is 4\n”end

def do_3() print “This is 3\n”end

Dispatcher = {

?2 =>instance_method(:do_2),

?1 =>instance_method(:do_1),

?4 =>instance_method(:do_4),

?3 =>instance_method(:do_3)

}

def interpret(string)

string.each_byte {|i| Dispatcher[i].bind(self).call }

end

end

interpreter = CommandInterpreter.new

interpreter.interpret(’1234′)

执行结果为:

This is 1

This is 2

This is 3

This is 4

3. 使用eval方法

我们还可以使用eval方法实现方法动态调用。eval方法在Kernel模块中定义,有多种变体如class_eval,module_eval,instance_eval等。Eval方法将分析其后的字符串参数并把这个字符串参数作为Ruby代码执行。

str = “Hello”

eval “str + ‘ World!’” =>Hello World!

sentence = %q{“This is a test!”.length}

eval sentence =>15

当我们在使用eval方法时,我们可以通过eval方法的第二个参数指明eval所运行代码的上下文环境,这个参数可以是Binding类对象或Proc类对象。Binding类封装了代码在某一环境运行的上下文,可以供以后使用。

class BindingTest

def initialize(n)

@value = n

end

def getBinding

return binding() #使用Kernel#binding方法返回一个Binding对象

end

end

obj1 = BindingTest.new(10)

binding1 = obj1.getBinding

obj2 = BindingTest.new(“Binding Test”)

binding2 = obj2.getBinding

puts eval(“@value”, binding1) #=>10

puts eval(“@value”, binding2) #=>Binding Test

puts eval(“@value”) #=>nil

可以看到上述代码中,@value在binding1所指明的上下文环境中值为10,在binding2所指明的上下文环境中值为Binding Test。当eval方法不提供binding参数时,在当前上下文环境中@value并未定义,值为nil。

本文在Windows7下测试成功。

安装和设置Git

下载Git for

Windows,采用默认安装,安装完成后就可以在本地使用Git了。

但要将内容放到Github上,必须先在Github网站上注册个账户,然后在本机使用Git创建SSH Key。操作如下:

在Git Bash上输入命令:

ssh-keygen -C "[email protected]" -t rsa

Note: “[email protected]”需要更换成你在Github上注册的Email地址或者是Username

这样会在用户目录(C:\Users\用户名)下产生一个.ssh文件夹,里面为对应的SSH

Keys,其中id_rsa.pub是Github需要的SSH公钥文件。

到c:\Users\用户名\.ssh\目录找到id_rsa.pub(可能位置不一定对,但是确认是以.pub结尾的文件),并用记事本打开复制全部内容。

Note:建议私钥公钥的名称最好写成"id_rsa",这样连接Github的时候会找这个文件,如果文件名已定,之后改名也行。

在github网站选择“Account Settings”>>“SSH Public Keys”>>“Add another

public key”,将刚才复制的内容粘贴到key文本框内。

这样就可以直接使用Git和GitHub了。

Note:建议在Git Bash中输入“ssh -v [email protected]”测试能够正常连接github

安装Ruby环境

下载RubyInstaller和DevKit。

因为Octopress需要的Ruby版本为1.9.2,所以选rubyinstaller-1.9.2-p290.exe,DevKit-tdm-32-4.5.2-20111229-1559-sfx.exe。

先安装RubyInstaller,然后解压缩DevKit(路径中不能有中文)。

在“Start Command Prompt with Ruby”命令行中进入DevKit解压缩的目录,然后运行以下命令:

ruby dk.rb init

ruby dk.rb install

gem install rdiscount --platform=ruby

如果安装成功,就可以使用一些Ruby的工具了,也为后面搭建博客提供了基础环境。

安装Octopress

先通过Git从Github上克隆一份Octopress(在Git Bash上输入命令)

git clone git://github.com/imathis/octopress.git octopress

然后安装一些依赖的工具(后面都是在Start Command Prompt with Ruby中输入)

cd octopress

ruby --version # Should report Ruby 1.9.2

gem install bundler

bundle install

安装Octopress默认的Theme

rake install

配置Octopress

将octopress的文件夹下的_config.yml的编码改成UTF-8:

保存(或另存为)时选择编码格式为UTF-8

修改_config.yml,批改url、title、subtitle、author等等。

到Ruby的安装目次\lib\ruby\gems\1.9.1\gems\jekyll-0.11.2\lib\jekyll\找到convertible.rb这个文件,批改self.content

= File.read(File.join(base, name))为self.content = File.read(File.join(base,

name), :encoding =>"utf-8")。

写博文

最简单的方式:复制octopress\source\_posts下某个文件,例如2012-07-30-the-first-post.markdown,修改文件名和文件中的内容

或者,命令行中输入rake

new_post["title"],会创建一个新的Post,新文件在source/_post下,文件名如下面的格式:2012-07-31-title.markdown。该文件可以直接打开修改。

写文章时,可以使用Markdown和Octopress

Plugins等工具对内容进行格式排版。

预览效果

在修改设置或者写完文章后,想看看具体效果,可以通过如下命令来完成:

rake generate

rake preview

将博客部署到Github上

在预览的效果符合自己的预期后,就可以通过如下命令将内容部署到Github上了。

如果是第一次部署,需要在Github上创建一个username.github.com的repository

在github网站选择“Create a New Repo”,如图

填写对应的内容即可

note:Repository

name填写username.github.com,username一定要和github的username一致,建好的博客代表的是你这个github账户的主页即page

配置octopress与github的连接:

进入Octopress目录:

rake setup_github_pages

按照提示填入你的github项目网址,比如:

[email protected]:Username/yourname.github.com.git

note:可以按照上面的修改,也可以在github的项目页中找地址

分发到github上:

rake deploy

第一次运行时,会询问是否建立对github的授权,输入:yes。然后将站点更新的内容推送到github上。

补充一点:

最后的但并不是最重要的,我们需要将修改的日志同步到github上,因此下面的3个命令也是必须的。

git status

git add .

git commit -m 'your message'

git push origin source

大功告成!

这个应用可以使用JavaConfig完成配置。我把它切分为下面几个部分:

ServicesConfig(服务配置)

无需扫描组件,配置真的非常简单:

@Configuration

public class ServicesConfig {

@Autowired

private AccountRepository accountRepository

@Bean

public UserService userService() {

return new UserService(accountRepository)

}