summaryrefslogtreecommitdiff
path: root/proc.c
diff options
context:
space:
mode:
authorzverok <zverok.offline@gmail.com>2023-02-15 21:52:59 +0200
committerVictor Shepelev <zverok.offline@gmail.com>2023-02-19 22:32:52 +0200
commit0258e92e432fad42a73982835f1f3b1f2f4f0a51 (patch)
tree735427858ec64b0e403318a249546a50b1bc3410 /proc.c
parent51bb5b23d499b02b670c9764fd1d51ef02d01c0a (diff)
downloadruby-0258e92e432fad42a73982835f1f3b1f2f4f0a51.tar.gz
[DOC] Improve Kernel#binding docs
* Add links to Binding class * Make examples practical * Extend possible usages description
Diffstat (limited to 'proc.c')
-rw-r--r--proc.c42
1 files changed, 35 insertions, 7 deletions
diff --git a/proc.c b/proc.c
index 6b6ed73832..38463ca03f 100644
--- a/proc.c
+++ b/proc.c
@@ -350,16 +350,44 @@ rb_binding_new(void)
* call-seq:
* binding -> a_binding
*
- * Returns a +Binding+ object, describing the variable and
+ * Returns a Binding object, describing the variable and
* method bindings at the point of call. This object can be used when
- * calling +eval+ to execute the evaluated command in this
- * environment. See also the description of class +Binding+.
+ * calling Binding#eval to execute the evaluated command in this
+ * environment, or extracting its local variables.
*
- * def get_binding(param)
- * binding
+ * class User
+ * def initialize(name, position)
+ * @name = name
+ * @position = position
+ * end
+ *
+ * def get_binding
+ * binding
+ * end
* end
- * b = get_binding("hello")
- * eval("param", b) #=> "hello"
+ *
+ * user = User.new('Joan', 'manager')
+ * template = '{name: @name, position: @position}'
+ *
+ * # evaluate template in context of the object
+ * eval(template, user.get_binding)
+ * #=> {:name=>"Joan", :position=>"manager"}
+ *
+ * Binding#local_variable_get can be used to access the variables
+ * whose names are reserved Ruby keywords:
+ *
+ * # This is valid parameter declaration, but `if` parameter can't
+ * # be accessed by name, because it is a reserved word.
+ * def validate(field, validation, if: nil)
+ * condition = binding.local_variable_get('if')
+ * return unless condition
+ *
+ * # ...Some implementation ...
+ * end
+ *
+ * validate(:name, :empty?, if: false) # skips validation
+ * validate(:name, :empty?, if: true) # performs validation
+ *
*/
static VALUE