我正在尝试获取哈希中某个键的索引。
我知道如何在数组中执行此操作:
arr = ['Done', 13, 0.4, true]
a = arr.index('Done')
puts a
是否有一种方法或某种方式使用哈希中的键来执行此操作?谢谢!
答案 0 :(得分:4)
至少有两种方法可以获取此信息,其中两种是Enumerable的find_index
方法,用于将每个元素传递给块并检查密钥:
hash.find_index { |key, _| key == 'Done' }
或者您可以从哈希中获取所有keys
作为数组,然后像往常一样查找索引:
hash.keys.index('Done')
答案 1 :(得分:4)
哈希通常不被视为有序结构,它们仅具有键列表和与这些键相对应的值。
的确,在Ruby中,哈希是按技术进行排序的,但是很少有实际的用例来处理它们。
如果要执行的操作是在哈希中找到与值对应的键,则只需使用Hash#key方法:
public class Helper
{
List<int> list = new List<int>();
public List<int> GetList
{
get
{
return list;
}
}
public async Task<bool> Process()
{
await Task.Delay(1);
//sleep this thread for 6 seconds
Thread.Sleep(6000);
//When I debug, both of the thread adds into the list
//but first thread always have zero element on this list, if it adds to the list then where it is getting lost ?
//not sure why ? Has to do something with the variable below _confighelper
//but why it behaves likes this ? what would be the best explanation?
//where this variable is getting lost ?
list.Add(1);
list.Add(2);
list.Add(3);
return true;
}
}
public class RunOp
{
//Has to do something with single instance
Helper _configHelper;
public async Task Run()
{
_configHelper = new Helper();
var val = await _configHelper.Process();
Console.WriteLine(_configHelper.GetList.Count);
}
}
class Program
{
static void Main(string[] args)
{
RunOp op = new RunOp();
Task.Factory.StartNew(async () =>
{
await op.Run();
});
Thread.Sleep(4000);
//Start another thread after 4 seconds
Task.Factory.StartNew(async () =>
{
await op.Run();
});
Console.ReadLine();
}
}
我想您可以使用hash = { a: 1, b: 2 }
hash.key(1) # => :a
来获取hash.keys.index(hash.key(1))
,因为它是第一个值,但是我也不建议这样做,因为这不是数据结构的典型用法