Project

General

Profile

Actions

Feature #12995

closed

Conditional expression taking a receiver outside the condition

Added by sawa (Tsuyoshi Sawada) almost 8 years ago. Updated over 7 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:78448]

Description

Since a conditional expression has a return value, we can continue a method chain after a conditional expression like this:

if hoge
  foo1.foo2.foo3
else
  bar1.bar2
end
.baz1.baz2.baz3.baz4
case hoge
when hoge1
  foo1.foo2.foo3
when hoge2
  bar1.bar2
end
.baz1.baz2.baz3.baz4

It is convenient if we can have a condition after or in the middle of a chain. I would like to do this:

baz1.baz2.baz3.baz4.
if hoge
  foo1.foo2.foo3
else
  bar1.bar2
end
baz1.baz2.baz3.baz4
if hoge
  .foo1.foo2.foo3
else
  .bar1.bar2
end
baz1.baz2.baz3.baz4.
case hoge
when hoge1
  foo1.foo2.foo3
when hoge2
  bar1.bar2
end
baz1.baz2.baz3.baz4
case hoge
when hoge1
  .foo1.foo2.foo3
when hoge2
  .bar1.bar2
end

Updated by herwinw (Herwin Quarantainenet) almost 8 years ago

You can do that with #tap. A very stupid example:

array = [true]
res = array.to_a.tap do |obj|
  if obj[0]
    obj.replace([['true', :val]])
  else
    obj.replace([['false', :val]])
  end
end.to_a.to_h
p res

Results in:

{"true"=>:val}

Updated by matz (Yukihiro Matsumoto) over 7 years ago

  • Status changed from Open to Rejected

Interesting proposal but this changes the meaning of if and case too much.

Matz.

Actions

Also available in: Atom PDF

Like0
Like0Like0