常见Ruby基础语法题
\n面试中常会遇到对变量作用域的考察。比如,局部变量、实例变量和类变量的区别。下面这段代码输出什么?
\nclass Person\n @@count = 0\n\n def initialize(name)\n @name = name\n @@count += 1\n end\n\n def self.total\n @@count\n end\nend\n\np1 = Person.new("Alice")\np2 = Person.new("Bob")\nputs Person.total # 输出:2\n\n字符串操作与符号对比
\nRuby里字符串(String)和符号(Symbol)经常被拿来比较。一个典型问题是::name 和 \"name\" 有什么不同?
\n符号是不可变的,且全局唯一,适合用作哈希键或方法名。而字符串可变,每次创建都会分配新内存。在实际项目中,比如写配置文件解析器时,用 Symbol 能提升性能。
\n\n数组与哈希常用方法考察
\n面试官喜欢让候选人手写实现 map 或 select 的功能。例如:
\ndef my_map(array)\n result = []\n for item in array\n result << yield(item)\n end\n result\nend\n\n# 使用\nsquares = my_map([1, 2, 3]) { |x| x ** 2 }\nputs squares.inspect # [1, 4, 9]\n\n块(Block)与yield机制
\n理解 block 是 Ruby 的核心之一。有道题常问:如何判断 block 是否传入?
\ndef do_something\n if block_given?\n yield\n else\n puts "No block provided."\n end\nend\n\ndo_something { puts "Hello!" } # Hello!\ndo_something # No block provided.\n\nProc与Lambda的区别
\n这两者都用于保存代码块,但行为略有差异。最明显的区别在参数检查和 return 行为上。
\nl = lambda { |x| puts x * 2 }\np = Proc.new { |x| puts x * 2 }\n\nl.call(5) # 正常输出 10\np.call(5) # 正常输出 10\n\nl.call # 报错:参数不足\np.call # 不报错,x 为 nil,输出 0\n\n面向对象设计相关问题
\n封装、继承、多态这些概念在 Ruby 中也有体现。比如,重写 to_s 方法让对象能友好打印:
\nclass Book\n attr_reader :title, :author\n\n def initialize(title, author)\n @title = title\n @author = author\n end\n\n def to_s\n \"《#{title}》 by #{author}\"\n end\nend\n\nbook = Book.new(\"Ruby入门指南\", \"张三\")\nputs book # 《Ruby入门指南》 by 张三\n\n模块Mixin的应用场景
\nRuby不支持多重继承,但可以用 Module 实现 mixin。比如定义一个日志功能:
\nmodule Loggable\n def log(message)\n puts "[LOG] #{Time.now}: #{message}"\n end\nend\n\nclass Worker\n include Loggable\n\n def work\n log("开始工作")\n # 模拟处理任务\n log("工作完成")\n end\nend\n\n异常处理机制
\n在编写脚本时,健壮性很重要。rescue 的使用频率很高。例如读取文件时防止崩溃:
\ndef read_config(file_path)\n File.read(file_path)\nrescue Errno::ENOENT => e\n puts "配置文件未找到:#{e.message}"\n {}\nrescue StandardError => e\n puts "读取失败:#{e.message}"\n nil\nend\n\n单例方法与 eigenclass
\n给某个对象单独添加方法,而不是整个类。这种技巧在测试或动态配置中很有用。
\nstr = \"hello\"\n\ndef str.shout\n self.upcase + \"!"\nend\n\nputs str.shout # HELLO!\n\nother_str = \"world\"\n# other_str.shout # 这行会报错,因为只有 str 有这个方法","seo_title":"Ruby脚本面试题整理 - 常见考点与代码示例详解","seo_description":"整理Ruby脚本常见的面试题,涵盖基础语法、块处理、面向对象设计等高频知识点,配有实用代码示例,帮助开发者高效准备技术面试。","keywords":"Ruby面试题,Ruby脚本,Ruby开发面试,编程题整理,Ruby代码示例"}