The value returned by a Ruby
method is the value of the last expression evaluated, so we can get rid of
the temporary variable and the return statement altogether.
Prefixing a method name with self. (as we do on line 5) makes it a class
method: it can be called on the class generally.
Instance variables are not directly accessible outside the class. To make
them available, write methods that return their values.
class Greeter
def initialize(name)
@name = name
end
def name
@name
end
def name=(new_name)
@name = new_name
end
end
The private directive is the strictest; private methods can be called only
from within the same instance. Protected methods can be called in the
same instance and by other instances of the same class and its subclasses.
Modules are similar to classes in that they hold a collection of methods,
constants, and other module and class definitions. Unlike classes, you
cannot create objects based on modules.
In Ruby,
that’s not the case; nil is an object, just like any other, that happens to
represent nothing.
So an ORM layer maps tables to classes, rows to objects, and columns to
attributes of those objects. Class methods are used to perform table-level
operations, and instance methods perform operations on the individual
rows.
By relying on convention and starting with sensible defaults,
Active Record minimizes the amount of configuration that developers perform.
Ruby statement modifiers are a useful shortcut if the body of an if or while statement
statement is just a single expression. Simply write the expression, followed
by if or while and the condition.
puts "Danger, Will Robinson" if radiation > 3000
In Ruby, you typically create a regular expression by
writing /pattern/ or %r{pattern}.
Marshaling Objects
本文介绍了Ruby语言的一些核心概念和编程技巧,包括方法返回值、类方法、实例变量、私有和受保护的方法、模块与类的区别、正则表达式的创建方式等。通过具体的代码示例,展示了如何使用这些特性进行高效编程。
2025

被折叠的 条评论
为什么被折叠?



