Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. def put_in_f(hash, keys, value)
  2. if keys.empty?
  3. value
  4. else
  5. car, cdr = [keys[0], keys[1..]]
  6. hash.merge(car => put_in_f(hash[car], cdr, value))
  7. end
  8. end
  9.  
  10. def extract(binding, ast)
  11. case ast.type
  12. when :SCOPE
  13. extract(binding, ast.children[2])
  14. when :CALL
  15. selv, methot, args = ast.children
  16. if methot == :[]
  17. keys, varname = extract(binding, selv)
  18. [[*keys, args.children[0].children[0]], varname]
  19. else
  20. raise NotImplementedError
  21. end
  22. when :DVAR
  23. [[], binding.local_variable_get(ast.children[0])]
  24. when :GVAR
  25. [[], eval(ast.children[0].to_s)]
  26. when :IVAR
  27. [[], binding.receiver.instance_variable_get(ast.children[0])]
  28. when :FCALL, :VCALL
  29. [[], binding.eval(ast.children[0].to_s)]
  30. else
  31. raise NotImplementedError, "ast.type #{ast.type} is not supported yet"
  32. end
  33. end
  34.  
  35. def put_in(b, value)
  36. ast = RubyVM::AbstractSyntaxTree.of(b)
  37. keys, hash = extract(b.binding, ast)
  38. put_in_f(hash, keys, 150)
  39. end
  40.  
  41. users = {
  42. ujihisa: {
  43. email: 'a@a.a',
  44. wallet: {
  45. money: 120,
  46. },
  47. },
  48. }
  49. users2 = put_in(-> { users[:ujihisa][:wallet][:money] }, 150)
  50. # this put_in behaves like
  51. # users.merge(ujihisa: users[:ujihisa].merge(wallet: users[:ujihisa][:wallet].merge(money: 150)))
  52. # to create an updated version of the given hash
  53. p users
  54. p users2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement