在irb我做
a = [1, 2, 3]
#=> [1, 2, 3]
a.class
#=> Array
a.methods.sort
#=> [:!, :!=, ..., :inject, ...]
Run Code Online (Sandbox Code Playgroud)
并得到a一个方法inject,但在http://www.ruby-doc.org/core-2.0/Array.html我找不到文档inject.为什么?这是Ruby API中的错误吗?
我在哪里可以找到有关Array实例方法的文档inject?
我有一个MyClass包含实例变量的类,@id并且@color:
class MyClass
attr_accessor :id, :color
end
Run Code Online (Sandbox Code Playgroud)
我创建了一个对象:
d = MyClass.new
d.id = 2
d.color = 'red'
d #=> #<MyClass:0x00000005fb52c0 @id=2, @color="red">
Run Code Online (Sandbox Code Playgroud)
我想获得一个包含实例变量及其值的哈希:
d.to_hash #=> { id: 2, color: 'red'}
Run Code Online (Sandbox Code Playgroud)
实施此类方法的最佳方法是什么?
我想通过跳过第一个数组的第一个字符串对字符串数组的数组进行排序,但我只是不知道如何使用内置sort方法进行排序。我可以复制没有第一个元素的整个数组,然后对结果数组进行排序,但是没有更优雅的方法来做到这一点吗?
ar = [["zzzz", "skip", "this"], ["EFP3","eins","eins"], ["EFP10","zwei","zwei"], ["EFP1","drei","drei"]]
ar.sort!{ |a,b|
if a == ar.first # why doesn't
next # this
end # work ?
# compare length, otherwise it would be e.g. 10 < 3
if a[0].length == b[0].length
a[0] <=> b[0]
else
a[0].length <=> b[0].length
end
}
Run Code Online (Sandbox Code Playgroud)
我想要这样的结果:
["zzzz", "skip", "this"], ["EFP1","drei","drei"], ["EFP3","eins","eins"], ["EFP10","zwei","zwei"]
Run Code Online (Sandbox Code Playgroud)
排序方式 "EFP#"
编辑:如果重要的话,我使用的是 Ruby 1.8。
我正在尝试将可汇总指标压缩到ruby表中的唯一标识符.
我有下表:
[["id1", 123], ["id2", 234], ["id1", 345]]
Run Code Online (Sandbox Code Playgroud)
压缩指标的最有效方法是什么,它看起来像这样:
[["id1", 468], ["id2", 234]]
Run Code Online (Sandbox Code Playgroud) entries哈希在哪里:
entries = { foo: 1, bar: 2 }
Run Code Online (Sandbox Code Playgroud)
这是我熟悉的语法:
entries.map { |key, val| "#{key} #{val}" }
#=> ["foo 1", "bar 2"]
Run Code Online (Sandbox Code Playgroud)
这是我在教程中遇到的语法:
entries.map { |key_val| "#{key_val.first} #{key_val.last}" }
#=> ["foo 1", "bar 2"]
Run Code Online (Sandbox Code Playgroud)
我是Ruby的新手,所以我很惊讶这两种语法都能正常工作.我的问题是:
这两者有什么区别吗?
为什么这样做 - 是因为哈希表对象以两种不同的方式实现Enumerable接口(提供map方法)?
我有一些方法:
def example_method
I ? world!
end
Run Code Online (Sandbox Code Playgroud)
我对这个方法有两个问题:
example_method不是我的方法),这种方法怎么可能不会返回错误.'I ? too!'字符串而不重新定义,重写此方法.第2点是我必须解决的练习.
谢谢!
我可以转换"+","-"或"/"运营商使用2.send("-",3)
但它不起作用 "+="
a = 2
a += 2 #=> 4
a = 2
a.send("+=", 4) #=> NoMethodError: undefined method `+=' for 2:Fixnum
Run Code Online (Sandbox Code Playgroud)
我试图先转换符号; 但也行不通;
怎么解决这个问题?
我有这个时区偏移格式的日期,我需要将其转换为 UTC 格式。例如:
日期 1 = 2017-07-13T17:13:12-04:00
date2_utc = 2017-07-13 21:13:12 UTC
我需要比较这两个日期是否相同。或者,如果我可以将 date1 转换为 UTC,那么我可以比较这两者。
我只是在学习Ruby,我想知道两者之间的区别
a += b
Run Code Online (Sandbox Code Playgroud)
和
a =+ b
Run Code Online (Sandbox Code Playgroud) 我有这个哈希:
h = {
124 => ["shoes", "59.99"],
456 => ["pants", "49.50"],
352 => ["socks", "3.99"]
}
Run Code Online (Sandbox Code Playgroud)
每个值都有两个元素.他们是一个名称(如"shoes","pants","socks")和价格(例如"59.99","49.50"和"3.99").我需要选择价格最高的价值.这124对价格来说至关重要"59.99".如何选择价格最高的哈希?
我试过这个:
h.select{ |x| x[1] }.max
#=> [456, ["pants", "49.50"]]
Run Code Online (Sandbox Code Playgroud)
但这给了我最大值并返回键456.