Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
メソッドインデックスがNILではなく-1を返す必要がありますが、別の方法はありますか?(Rubyプログラミング)
index="asddsa".index("/") if index==nil puts -1 else puts index end
自分でやってください:
index = "asddsa".index("/") || -1
これが機能するのは、式がifが/でない場合にa = b || c割り当てbられ、is /の場合、代わりにに割り当てられるためです。したがって、この場合、を返すと、変数に割り当てられます(そして、数値を返すと、それがに割り当てられます)。abnilfalsebnilfalsecaString#indexnil-1indexindex
a = b || c
b
a
nil
false
c
String#index
-1
index