Skip to content

Instantly share code, notes, and snippets.

@pokk
Created August 18, 2017 06:53
Show Gist options
  • Save pokk/9f7854af504b77c5d36e7088bdf98358 to your computer and use it in GitHub Desktop.
Save pokk/9f7854af504b77c5d36e7088bdf98358 to your computer and use it in GitHub Desktop.
Ruby has magic candy function as Kotlin

[TOC]

Introduction

Ruby and Kotlin have the same magic candy function!

What's kind of magic candy function?

Kotlin

  • apply (also)
  • let
  • with
  • run

Ruby

  • tap
  • try

How to use

apply vs tap

In the Kotlin

Car.builder().apply {
  name = "Benz"
  speed = 500
  age = 3
}

In the Ruby

Car.new.tap { |car|
  car.name = 'Benz'
  car.speed = 500
  car.age = 3
}

let vs try

In the Kotlin

val msg: String? = "Hello World"

msg?.let {
    tell_other(msg)
    println(msg)
}

In the Ruby

msg.try { |it|
  tell_other(it)
  p it
}

# or in Hash or Object
h = {name: 'jieyi', address: nil}

h.try(:address) { |addr|
  p addr
}

*** Note: let & try are the same function. try will return the instruction of the end block line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment