我想从对象存储和检索一些变量.例如在a
a = "a"
Run Code Online (Sandbox Code Playgroud)
到目前为止,我发现了两种可能的方法.
使用instance_variable_set和instance_variable_get
a.instance_variable_set(:@x, 10)
a.instance_variable_get(:@x) # => 10
Run Code Online (Sandbox Code Playgroud)或者只是使用 instance_eval
a.instance_eval { @y = 5 }
a.instance_eval { @y } # => 5
Run Code Online (Sandbox Code Playgroud)对我来说第二种方法看起来更短更简单,如果我喜欢这个,我的代码有什么问题吗?
我想编写方法(define_variables),它可以获得block并使用其中定义的变量.可能吗?例如,我想输出5:
module A
def self.define_variables
yield
puts a # not 5 :(
end
end
A::define_variables do
a = 5
end
Run Code Online (Sandbox Code Playgroud)
也许有一些eval的技巧,但还没有找到任何人.
例如,我有一个这样的字符串日期(我是从 json 中的服务器,从 rails 应用程序中获取的)
s = "2013-09-01T00:00:00.000+08:00"
Run Code Online (Sandbox Code Playgroud)
我想这样显示
01.09.2013
Run Code Online (Sandbox Code Playgroud)
所以我为此使用 moment.js 库
moment(s).zone("+08:00").format("DD.MM.YYYY")
>> "01.09.2013"
Run Code Online (Sandbox Code Playgroud)
但我不知道是否需要时区是 +08:00。如果我跳过.zone()通话,结果将是错误的,因为我的浏览器处于不同的时区
moment(s).format("DD.MM.YYYY")
>"31.08.2013"
Run Code Online (Sandbox Code Playgroud)
即使在我最后的原始字符串中+08:00。
所以,我的问题是如何使用纯 javascript 或 moment.js 库从 json 日期字符串中提取时区?
我能想到的最简单的方法是手动提取最后 6 个字符,
s.slice(s.length - 6, s.length)
> "+08:00"
Run Code Online (Sandbox Code Playgroud)
但也许有更好的方法来完成这项任务?
是否可以使用设计自动根据自己的电子邮件创建用户名?
在注册页面上,我只有电子邮件和密码字段.
例如,当用户使用电子邮件创建新帐户时randomname@gmail.com,我希望他的用户名自动成为randomname.我怎么能完成它?
我有一个数组 this.colors = [RED, BLUE, GREEN],有时我想从这个数组中选择一个随机颜色.当我这样做时,结果是正常的:
rand_color = this.colors[Math.floor(Math.random() * this.colors.length)]
javascript: console.log(rand_color)
// => rgb(211, 65, 65)
Run Code Online (Sandbox Code Playgroud)
但是当我把它包装在函数中时:
this.pick_random_color = function() {
return this.colors[Math.floor(Math.random() * this.colors.length)];
}
Run Code Online (Sandbox Code Playgroud)
该函数不返回随机值.相反,我在日志中收到此消息:
color = this.pick_random_color;
javascript: console.log(color);
// => this.pick_random_color = function() {
// => return this.colors[Math.floor(Math.random() * this.colors.length)];
// => }
Run Code Online (Sandbox Code Playgroud)
这个功能出了什么问题?
我想textarea在发生某些事件时添加文本"username" ,并且此代码有效
$("textarea").append("username")
Run Code Online (Sandbox Code Playgroud)
确切地说,直到我textarea手动添加一些文本.如何避免这种行为?这就是我在html源码上的内容.
<a href="javascript:void(0)" onclick="javascript:add_to_textarea('User')">User</a>
Run Code Online (Sandbox Code Playgroud) 是否有可能不直接改变对象的价值?
例如
a = {x: 5}
b = a.x
b = 100
a.x // => 5
Run Code Online (Sandbox Code Playgroud)
我想要100,但实际上,a.x仍然是5.