Ask A Question

Notifications

You’re not receiving notifications from this thread.

migrating to php

vampster asked in Ruby

Hello,
I have inherited a ruby application and unfortunately have no knowledge of the language.
Could someone be so kind to help me figure out how to convert the below code to php?

  def generate_md5(*args)
    digest = Digest::MD5.new
    for arg in args do
      digest << arg.to_s
    end
    digest.hexdigest
  end

I have tried to get the same output in php, but I am failing.
I do not understand what happens in the for each loop.
The << seems to be equivalent to "update". What exactly does this update do?
Does it use the original hash, concatenate the new argument to it and hash the resulting string?
(this does not seem to generate the same output in php)
Or am I completely misunderstanding this (which is quite likely....)?

Reply

Hey vampster,

Does it use the original hash, concatenate the new argument to it and hash the resulting string?

In this particular case, yes. So for example if you have var = 'foo' and then var << 'bar' the value of var will now be 'foobar'

> digest = Digest::MD5.new
=> #<Digest::MD5: d41d8cd98f00b204e9800998ecf8427e>
> digest << "foo"
=> #<Digest::MD5: acbd18db4cc2f85cedef654fccc4a4d8>
> digest << "bar"
=> #<Digest::MD5: 3858f62230ac3c915f300c664312c63f>
> digest.hexdigest
=> "3858f62230ac3c915f300c664312c63f"
> var = 'foo'
=> "foo"
> var << 'bar'
=> "foobar"
> var
=> "foobar"

Check out https://medium.com/@AdamLombard/easy-ruby-plus-equals-vs-shovel-6f030875e366 if you want more details on the << function

Reply

Thanks for your help Jacob. I understand better now.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,972+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.