MST

星途 面试题库

面试题:Ruby数组与哈希的基本操作

请编写一段Ruby代码,实现以下功能:有一个数组,包含一些水果名称(如 ['apple', 'banana', 'cherry']),创建一个哈希,键为水果名称,值为水果名称的长度。然后遍历这个哈希,将键值对以特定格式(例如:“水果名: 长度”)打印出来。
26.6万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
fruits = ['apple', 'banana', 'cherry']
fruit_hash = {}
fruits.each do |fruit|
  fruit_hash[fruit] = fruit.length
end

fruit_hash.each do |key, value|
  puts "#{key}: #{value}"
end