我想要的是:
obj = Foo.new(0) # => nil or false
Run Code Online (Sandbox Code Playgroud)
这不起作用:
class Foo
def initialize(val)
return nil if val == 0
end
end
Run Code Online (Sandbox Code Playgroud)
我知道在C/C++/Java/C#中,我们无法在构造函数中返回一个值.
但我想知道Ruby是否可行.
现在是时候缩短它了:
class Foo
attr_accessor :a, :b, :c, :d, :e
def initialize(a, b, c, d, e)
@a = a
@b = b
@c = c
@d = d
@e = e
end
end
Run Code Online (Sandbox Code Playgroud)
我们有'attr_accessor'来生成getter和setter.
我们有什么要按属性生成初始值设定项吗?
def bar(foo)
foo.nil? ? nil : foo.to_i
end
Run Code Online (Sandbox Code Playgroud)
任何简洁的Ruby成语都是"foo.nil??nil:foo.to_i"?
我知道我们可以在C#中使用{{和转义大括号}}.但是如果它们在格式修饰符(如{0:F6})之后,它们似乎不能很好地工作.
string str;
// Prints "{3.14}" as expected
str = string.Format("{{{0}}}", 3.14);
Console.WriteLine(str);
// Expected "{3.140000}", found "{F6}"
str = string.Format("{{{0:F6}}}", 3.14);
Console.WriteLine(str);
Run Code Online (Sandbox Code Playgroud) 在Ruby中,可以通过Set [1,2,3]初始化一个集合.所以可以使用数组:Array [1,2,3]
是否可以编写一些代码来对我自己的类做同样的事情?或者它只是少数几个内置类的语言功能?